简体   繁体   English

将 Pandas 数据帧转换为 JSON 文件

[英]Converting a pandas dataframe to JSON file

I am trying to convert a pandas DataFrame to JSON file.我正在尝试将 Pandas DataFrame 转换为 JSON 文件。 Following image shows my data: Screenshot of the dataset from Ms. excel下图显示了我的数据:来自 Ms. excel 的数据集的屏幕截图

I am using the following code:我正在使用以下代码:

import pandas as pd

os.chdir("G:\\My Drive\\LEC dashboard\\EnergyPlus simulation files\\DEC\\Ahmedabad\\Adaptive set point\\CSV")

df = pd.read_csv('Adap_40-_0_0.1_1.5_0.6.csv')
df2 = df.filter(like = '[C](Hourly)',axis =1)
df3 = df.filter(like = '[C](Hourly:ON)',axis =1)
df4 = df.filter(like = '[%](Hourly)',axis =1)
df5 = df.filter(like = '[%](Hourly:ON)',axis =1)

df6 = pd.concat([df2,df3,df4,df5],axis=1)
df6.to_json("123.json",orient='columns')

I the output, I am getting a dictionary in of values.我的输出,我得到一个值的字典。 However, I need a list as value.但是,我需要一个列表作为值。

The output I am getting: The JSON output I am getting by using above code我得到的输出:我使用上面的代码得到的 JSON 输出

The out put that is desired: The output that is desired.期望的输出:期望的输出。

I have tried different orientations of json but nothing works.我尝试了 json 的不同方向,但没有任何效果。

There might be other ways of doing this but one way is this.可能还有其他方法可以做到这一点,但一种方法是这样。

import json
test = pd.DataFrame({'a':[1,2,3,4,5,6]})
with open('test.json', 'w') as f:
    json.dump(test.to_dict(orient='list'), f)

Result file will look like this '{"a": [1, 2, 3, 4, 5, 6]}'结果文件看起来像这样'{"a": [1, 2, 3, 4, 5, 6]}'

There is a built-in function of pandas called to_json: pandas 有一个内置函数叫做 to_json:

df.to_json(r'Path_to_file\file_name.json')

Take a look at the documentation if you need more specifics: https://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.to_json.html如果您需要更多细节,请查看文档: https : //pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.to_json.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM