熊猫DataFrame转换成JSON格式文件

2024-05-14 16:08:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试生成以下格式的文本文件:

{"0": ["n01440764", "tench"], "1": ["n01443537", "goldfish"], "2": ["n01484850", "great_white_shark"]}

我在数据帧中输入了数据:

^{pr2}$

我试过:

df.to_json(PATH/'my_file.json', orient='index')

json_f = json.dumps(df.to_dict(orient='list'))
with open(PATH/'my_file.json', 'w') as outfile:
    json.dump(json_tiny, outfile)

以及各种各样的变体,但无法解决如何生成格式正确的输出文件。蚂蚁的主意?在


Tags: to数据pathjsondfmy格式outfile
1条回答
网友
1楼 · 发布于 2024-05-14 16:08:26

您需要一个名为“list”的特定方向,to_json不提供,但to_dict提供。在

import json

with open('my_file.json', 'w') as f:
    json.dump(df.T.to_dict(orient='list'), f)

my_file.json

^{pr2}$

相关问题 更多 >

    热门问题