我想将数据框转换为json并以漂亮的打印格式将其转储到文件中。 我尝试过-
df.to_json(r'C:\users\madhur\Desktop\example.json,'orient = 'index')
上面的代码在json中转储,但是在一行中。
我也尝试过
import json
hello = df.to_json(orient = 'index')
with open(r'C:\users\madhur\Desktop\example.json','a') as f:
json.dump(hello,f,indent=4,sort_keys=True)
但是上面的代码给出的是单行输出,输出在双反逗号前有一个'\'
。
输出看起来像-
“ {\” 17668620_INCOLL \“:{\” DRWECNTRY \“:\”新西兰........“
如果有人对此查询有任何建议,答案或需要更多信息,请发表评论/答案。
注意-我正在使用Python 3.6
答案 0 :(得分:1)
您可以直接传递indent = int
:
df.to_json(r'example.json', orient='index', indent=2 )
答案 1 :(得分:1)
如果您只想复制REPL中的粘贴内容,请使用df.to_dict(orient='records')