[英]Pandas DataFrame to JSON format file
I am trying to generate a text file with the following format: 我正在尝试生成以下格式的文本文件:
{"0": ["n01440764", "tench"], "1": ["n01443537", "goldfish"], "2": ["n01484850", "great_white_shark"]}
I have input data in a DataFrame: 我在DataFrame中输入了数据:
data = [('n02124075', 'egyptian_cat'),
('n04067472', 'reel'),
('n04540053', 'volleyball')]
df = pd.DataFrame(data)
df.head(n=2)
0 1
0 n02124075 egyptian_cat
1 n04067472 reel
I have tried: 我努力了:
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)
and various variations of these but cant work out how to generate output file with correct format. 以及这些的各种变体,但无法弄清楚如何以正确的格式生成输出文件。 Ant ideas?
蚂蚁的想法?
You'll need a specific orient called "list" that to_json
does not offer, but to_dict
does. 您需要一个特定的名为“列表”的东方,
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
{
"0": ["n02124075", "egyptian_cat"],
"1": ["n04067472", "reel"],
"2": ["n04540053", "volleyball"]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.