pandas 将熊猫数据帧转换为 json 对象 - 熊猫

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50384883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:34:00  来源:igfitidea点击:

convert pandas dataframe to json object - pandas

pythonpandas

提问by jason

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.

我正在使用df.to_json()将数据帧转换为 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.

此外,当我将此数据附加到数组时,它会在 json 前后添加单引号,并破坏了 json 结构。如何导出到 json 对象并正确附加。

Code used:

使用的代码

a=[]
     array.append(df1.to_json(orient='records', lines=True)) 
     array.append(df2.to_json(orient='records', lines=True)) 

Result:

结果

['{"test:"w","param":1}','{"test:"w2","param":2}]']

Required Result:

要求的结果

[{"test":"w","param":1},{"test":"w2","param":2}]

回答by jezrael

I believe need create dict and then convert to json:

我相信需要创建 dict 然后转换为json

import json
d = df1.to_dict(orient='records')
j = json.dumps(d)

Or if possible:

或者如果可能的话:

j = df1.to_json(orient='records')

回答by igorkf

Here's what worked for me:

这是对我有用的:

import pandas as pd
import json

df = pd.DataFrame([{"test":"w","param":1},{"test":"w2","param":2}])
print(df)
    test  param
0     w      1
1    w2      2

So now we convert to a json string:

所以现在我们转换为 a json string

d = df.to_json(orient='records')
print(d)
'[{"test":"w","param":1},{"test":"w2","param":2}]'

And now we parse this string to a list of dicts:

现在我们将此字符串解析为一个字典列表:

data = json.loads(d)
print(data)
[{'test': 'w', 'param': 1}, {'test': 'w2', 'param': 2}]