问题描述
我有一个熊猫DataFrame
,其中有两列-一列是文件名,一列是生成小时的时间:
I have a Pandas DataFrame
with two columns – one with the filename and one with the hour in which it was generated:
File Hour
F1 1
F1 2
F2 1
F3 1
我正在尝试将其转换为以下格式的JSON文件:
I am trying to convert it to a JSON file with the following format:
{"File":"F1","Hour":"1"}
{"File":"F1","Hour":"2"}
{"File":"F2","Hour":"1"}
{"File":"F3","Hour":"1"}
当我使用命令DataFrame.to_json(orient = "records")
时,我得到以下格式的记录:
When I use the command DataFrame.to_json(orient = "records")
, I get the records in the below format:
[{"File":"F1","Hour":"1"},
{"File":"F1","Hour":"2"},
{"File":"F2","Hour":"1"},
{"File":"F3","Hour":"1"}]
我只是想知道是否有一个选项来获取所需格式的JSON文件.任何帮助将不胜感激.
I'm just wondering whether there is an option to get the JSON file in the desired format. Any help would be appreciated.
推荐答案
您在 DF.to_json
是string
.因此,您可以根据需要简单地对其进行切片,并从中删除逗号.
The output that you get after DF.to_json
is a string
. So, you can simply slice it according to your requirement and remove the commas from it too.
out = df.to_json(orient='records')[1:-1].replace('},{', '} {')
要将输出写入文本文件,您可以执行以下操作:
To write the output to a text file, you could do:
with open('file_name.txt', 'w') as f:
f.write(out)
这篇关于将Pandas DataFrame转换为JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!