我正在尝试转换一个熊猫的DataFrame到JSON文件。下图显示了我的数据:Screenshot of the dataset from Ms. excel
我使用了以下代码:
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')在输出中,我得到了一本关于值的字典。但是,我需要一个列表作为值。
我得到的输出是:The JSON output I am getting by using above code
所需的输出:The output that is desired.
我尝试过不同方向的json,但都不起作用。
发布于 2020-02-18 16:29:45
可能还有其他方法可以做到这一点,但有一种方法就是这样。
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)结果文件将如下所示的'{"a": [1, 2, 3, 4, 5, 6]}'
发布于 2020-02-18 17:56:01
pandas有一个内置的函数,叫做to_json:
df.to_json(r'Path_to_file\file_name.json')如果您需要更多细节,请查看文档:https://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.to_json.html
https://stackoverflow.com/questions/60274552
复制相似问题