Pandas 数据帧到 json 没有索引
Pandas dataframe to json without index
我正在尝试获取数据帧并将其转换为特定的 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"!任何帮助将不胜感激。
您可以使用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]"}
]
如果您想要 Python dict(python 中的 JSON-object 等价物)而不是 JSON 字符串:
df.to_dict(orient='records')
自 2017 年以来,有一个 index=False
选项。与 orient='split'
或 orient='table'
一起使用。感谢这个关于类似问题的答案:
dfj = json.loads(df.to_json(orient='table',index=False))
还有一种方法。
df_dict=df.reset_index().to_dict(orient='index')
df_vals=list(df_dict.values())
我正在尝试获取数据帧并将其转换为特定的 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"!任何帮助将不胜感激。
您可以使用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]"}
]
如果您想要 Python dict(python 中的 JSON-object 等价物)而不是 JSON 字符串:
df.to_dict(orient='records')
自 2017 年以来,有一个 index=False
选项。与 orient='split'
或 orient='table'
一起使用。感谢这个关于类似问题的答案:
dfj = json.loads(df.to_json(orient='table',index=False))
还有一种方法。
df_dict=df.reset_index().to_dict(orient='index')
df_vals=list(df_dict.values())