将pandas数据框转换为json对象-pandas [英] convert pandas dataframe to json object - pandas
本文介绍了将pandas数据框转换为json对象-pandas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用df.to_json()
将数据帧转换为json.但这给了我一个json字符串,而不是一个对象.如何获取json对象.
I'm using df.to_json()
to convert dataframe to json. But it gives me a json string and not an object. How can I get json object.
此外,当我将此数据附加到数组时,它在json前后添加单引号,并且破坏了json结构.如何导出到json对象并正确附加.
Also, when I'm appending this data to an array, it adds single quote before and after the json and it ruins the json structure. How can I export to json object and append properly.
使用的代码:
a=[]
array.append(df1.to_json(orient='records', lines=True))
array.append(df2.to_json(orient='records', lines=True))
结果:
['{"test:"w","param":1}','{"test:"w2","param":2}]']
所需结果:
[{"test":"w","param":1},{"test":"w2","param":2}]
推荐答案
我认为需要创建dict,然后转换为json
:
I believe need create dict and then convert to json
:
import json
d = df1.to_dict(orient='records')
j = json.dumps(d)
或者,如果可能的话:
j = df1.to_json(orient='records')
这篇关于将pandas数据框转换为json对象-pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文