📜  将 Pandas DataFrame 导出为 JSON 文件

📅  最后修改于: 2022-05-13 01:54:25.293000             🧑  作者: Mango

将 Pandas DataFrame 导出为 JSON 文件

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

示例 1:

Python3
# 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)


Python3
# 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 文件。

示例 2

Python3

# 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 文件。