【问题标题】:How to turn pandas table values into a specific json format?如何将 pandas 表值转换为特定的 json 格式?
【发布时间】:2020-06-20 09:04:18
【问题描述】:

例如,让我们看一下下面的 PANDAS 表: sample_pandas

问题:我怎样才能创建一个返回这个的 json 文件:

{"data": 
[ 
[a1, a2, a3], 
[b1, b2, b3],
[c1, c2, c3]
]
}

我知道在熊猫中,你可以得到每个条目

list(list(df.values)[i])

请帮忙!

【问题讨论】:

标签: python json pandas list


【解决方案1】:

你可以试试这个代码

import pandas
import json

df = pandas.DataFrame([['a1', 'a2','a3'], ['b1', 'b2','b3'],['c1','c2','c3']],
                  index=['row 1', 'row 2','row 3'],
                  columns=['col 1', 'col 2','col 3'])

df.to_json(r'1Export_DataFrame.json',orient='values')


with open('1Export_DataFrame.json') as f:
  data = json.load(f)


test_dict = {"data": data
}

with open('test.json', 'w') as json_file:
  json.dump(test_dict, json_file)

根据您的问题要求打开 test.json 文件以获得预期的输出

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    来自this的帖子,您可以:

    df = pd.DataFrame('your input')
    your_json = df.to_json(orient='split')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 2017-12-18
      • 1970-01-01
      • 2017-01-08
      相关资源
      最近更新 更多