将Pandas数据框转换为JSON格式但不包含索引。

47

我想把一个数据框转换成特定的JSON格式。

这是我的数据框示例:

DataFrame name: Stops
id    location
0     [50, 50]
1     [60, 60]
2     [70, 70]
3     [80, 80]

这是我想要转换成的JSON格式:

"stops":
[
{
    "id": 1,
    "location": [50, 50]
},
{
    "id": 2,
    "location": [60, 60]
},
... (and so on)
]

注意这是一个字典列表。以下代码就可以接近完成:

df.reset_index().to_json(orient='index')

不过,这行代码会把索引也包含进去:

"stops":
{
"0":
    {
        "id": 0,
        "location": [50, 50]
    },
"1":
    {
        "id": 1,
        "location": [60, 60]
    },
... (and so on)
}

请注意,这是一个字典的字典,并且包括两次索引(在第一个字典中和作为第二个字典中的"id"!任何帮助将不胜感激。


也许行为改变了?我收到了“ValueError: too many values to unpack (expected 2)”错误。 - WestCoastProjects
4个回答

86

你可以使用 orient='records'

print df.reset_index().to_json(orient='records')

[
     {"id":0,"location":"[50, 50]"},
     {"id":1,"location":"[60, 60]"},
     {"id":2,"location":"[70, 70]"},
     {"id":3,"location":"[80, 80]"}
]

3
那很简单。我喜欢熊猫...还有你!谢谢! - Eric Miller
6
如果您不想要索引,只需删除“reset_index()”部分即可。 - aerin
在偶然的情况下发现了这个。 - prosti

4
自2017年起,有一个index=False选项。将其与orient='split'orient='table'一起使用。参考类似问题的这个答案:https://dev59.com/pVcP5IYBdhLWcg3w8eS4#59438648
    dfj = json.loads(df.to_json(orient='table',index=False))

3
如果您需要一个Python dict(Python中的JSON对象),而不是一个JSON字符串:
df.to_dict(orient='records')

2

还有一种方法。

df_dict=df.reset_index().to_dict(orient='index')
df_vals=list(df_dict.values())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接