pandas|解析JSON数据与导出

使用pandas解析JSON Dataset要方便得多。Pandas允许您将列表的列表转换为Dataframe并单独指定列名。
JSON解析器将JSON文本转换为另一种表示必须接受符合JSON语法的所有文本。它可以接受非JSON形式或扩展。实现可以设置以下内容:

  • 它接受的文本大小的限制,
  • 对嵌套的最大深度的限制,
  • 对数字范围和精度的限制,
  • 设置字符串的长度和字符内容的限制。

使用大型JSON数据集可能会恶化,特别是当它们太大而无法容纳在内存中时。在这种情况下,命令行工具和Python的组合可以成为探索和分析数据的有效方法。

导入JSON文件

JSON的操作是使用Python数据分析库pandas完成的。

import pandas as pd

现在,您可以使用命令read_json读取JSON并将其保存为pandas数据结构。

pandas.read_json (path_or_buf=None, orient = None, typ=’frame’, dtype=True, convert_axes=True, convert_dates=True, keep_default_dates=True, numpy=False, precise_float=False, date_unit=None, encoding=None, lines=False, chunksize=None, compression=’infer’)


import pandas as pd
# Creating Dataframe 
df = pd.DataFrame([['a', 'b'], ['c', 'd']],
                  index =['row 1', 'row 2'],
                  columns =['col 1', 'col 2'])
  
# Indication of expected JSON string format
print(df.to_json(orient ='split'))
  
print(df.to_json(orient ='index'))

输出:

{"columns":["col 1", "col 2"],
 "index":["row 1", "row 2"],
 "data":[["a", "b"], ["c", "d"]]}

{"row 1":{"col 1":"a", "col 2":"b"},
 "row 2":{"col 1":"c", "col 2":"d"}}

转换object对象到json数据使用dataframe.to_json

DataFrame.to_json(path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit=’ms’, default_handler=None, lines=False, compression=’infer’, index=True)

直接从Dataset读取JSON文件:

import pandas as pd
  
data = pd.read_json('http://api.population.io/1.0/population/India/today-and-tomorrow/?format = json')
print(data)

输出:

total_population
0  {'date': '2019-03-18', 'population': 1369169250}
1  {'date': '2019-03-19', 'population': 1369211502}

使用Pandas进行嵌套JSON解析:

嵌套的JSON文件可能非常耗时,并且很难将其展平并加载到Pandas中。
我们使用嵌套的“'raw_nyc_phil.json。"'从一个嵌套数组创建一个扁平化的pandas数据框,然后解包一个深度嵌套数组。

import json
import pandas as pd
from pandas.io.json import json_normalize

with open('https://github.com/a9k00r/python-test/blob/master/raw_nyc_phil.json') as f:
	d = json.load(f)

# lets put the data into a pandas df
# clicking on raw_nyc_phil.json under "Input Files"
# tells us parent node is 'programs'
nycphil = json_normalize(d['programs'])
nycphil.head(3)

在这里插入图片描述

works_data = json_normalize(data = d['programs'],
							record_path ='works',
							meta =['id', 'orchestra', 'programID', 'season'])
works_data.head(3)

在这里插入图片描述

soloist_data = json_normalize(data = d['programs'],
							record_path =['works', 'soloists'],
							meta =['id'])

soloist_data.head(3)

在这里插入图片描述

将Pandas DataFrame导出到JSON文件

让我们看看如何将Pandas DataFrame导出为JSON文件。要执行此任务,我们将使用DataFrame.to_json()和pandas.read_json()函数。

示例1:

# importing the module
import pandas as pd

# creating a DataFrame
df = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']],
				index =['row 1', 'row 2', 'row3'],
				columns =['col 1', 'col 2', 'col3'])

# storing the data in JSON format
df.to_json('file.json', orient = 'split', compression = 'infer', index = 'true')

# reading the JSON file
df = pd.read_json('file.json', orient ='split', compression = 'infer')

# displaying the DataFrame
print(df)

在这里插入图片描述
我们可以看到DataFrame已经导出为JSON文件。
在这里插入图片描述

示例2:


# importing the module
import pandas as pd
  
# creating a DataFrame
df = pd.DataFrame(data = [['15135', 'Alex', '25 / 4/2014'],
                   ['23515', 'Bob', '26 / 8/2018'],
                   ['31313', 'Martha', '18 / 1/2019'],
                   ['55665', 'Alen', '5 / 5/2020'],
                   ['63513', 'Maria', '9 / 12 / 2020']],
                  columns =['ID', 'NAME', 'DATE OF JOINING'])
 
# storing data in JSON format
df.to_json('file1.json', orient = 'split', compression = 'infer')
 
# reading the JSON file
df = pd.read_json('file1.json', orient ='split', compression = 'infer')
print(df)

在这里插入图片描述
我们可以看到这个DataFrame也被导出为JSON文件。
在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实验23: CSV、JSON格式与数据清洗 CSV(逗号分隔值)和JSON(JavaScript对象表示法)是常见的数据交换格式,它们在数据清洗和数据处理中起着重要的作用。 首先,CSV是一种用于将表格数据存储为纯文本的格式。每行由逗号分隔成不同的字段,每个字段代表表格的一列。CSV文件易于阅读和编写,并且几乎所有的电子表格软件和数据库都支持导入和导出CSV文件。在数据清洗过程中,我们可以使用CSV文件读取库(如pandas)将CSV文件加载到内存中,然后进行各种数据处理操作,如数据过滤、数据转换和数据聚合等。 与CSV相比,JSON是一种更灵活和复杂的数据交换格式。JSON以键值对的形式存储数据,可以包含多个级别的嵌套结构。JSON文件可以用于表示结构化和半结构化的数据,并且广泛应用于Web应用程序和API中。在数据清洗过程中,我们可以使用JSON文件解析库(如json库)将JSON文件加载到内存中,然后使用各种处理技术对数据进行清洗和转换。 数据清洗是指对原始数据进行处理,以去除错误、重复、缺失和不一致的数据,以提高数据质量。在实验23中,我们可以使用CSV和JSON格式对原始数据进行清洗。例如,我们可以使用pandas库读取CSV文件,然后使用pandas数据清洗功能对数据进行清洗。对于JSON格式的数据,可以使用json库加载和解析JSON文件,然后进行数据清洗。 总之,CSV和JSON是常见的数据交换格式,在实验23中可以用于数据清洗。通过了解和使用这些格式,我们可以更好地处理和分析数据,提高数据的准确性和一致性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值