【问题标题】:Converting a pandas dataframe to JSON file将 pandas 数据帧转换为 JSON 文件
【发布时间】:2020-02-18 05:53:33
【问题描述】:

我正在尝试将 pandas 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 的不同方向,但没有任何效果。

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    可能还有其他方法可以做到这一点,但其中一种方法就是这样。

    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]}'

    【讨论】:

    • 所以你是说我需要将我的数据框转换为字典?
    • 一种解决方法是使用其他 JSON 库,例如 rapidjsonlink repo 来写入数据。至少在我的本地基准测试中,它比默认的 json 库要快。
    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 2018-10-27
      • 2020-10-30
      • 2018-06-15
      • 2020-02-29
      • 2017-02-04
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多