目录
Pandas是一个功能强大的用于数据处理的Python库,它提供了to_json()函数将DataFrame转换为JSON文件,以及read_json()函数将JSON文件读取为DataFrame。在本文中,我们将通过详细的解释和适合初学者的步骤,探索如何将Pandas DataFrame导出为JSON文件。
将Pandas DataFrame导出为JSON
我们使用to_json()函数将Pandas DataFrame导出为JSON文件。
示例1:导出简单的DataFrame
这个示例展示了如何创建一个包含三行三列的小型DataFrame,并将其保存为JSON文件。
import pandas as pd
df = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']],
index=['row 1', 'row 2', 'row 3'],
columns=['col 1', 'col 2', 'col 3'])
df.to_json('file.json', orient='split', compression='infer', index=True)
df = pd.read_json('file.json', orient='split', compression='infer')
print(df)
编辑
示例2:导出更详细的DataFrame
在这个例子中,我们创建了一个包含员工详细信息(如员工ID、姓名和入职日期)的DataFrame。JSON文件使用split导出,这种方式通过分别存储索引、列名和值来高效地组织数据。
import pandas as pd
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'])
df.to_json('file1.json', orient='split', compression='infer')
df = pd.read_json('file1.json', orient='split', compression='infer')
print(df)
编辑
Pandas创建不同样式的JSON
Pandas支持JSON格式的多种orient选项,允许以不同方式来组织数据。
- • records:字典列表
- • columns:带列标签的字典
- • index:带行索引的字典
- • split:带索引、列和数据的字典
- • table:JSON表模式