Pandas dataframe到json,不带索引

2024-06-01 08:01:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获取一个数据帧并将其转换为部分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)
}

注意,这是一个dict的dict,还包含两次索引(在第一个dict中,作为第二个dict中的“id”!任何帮助都将不胜感激。


Tags: and数据nameidjson示例dataframeindex
1条回答
网友
1楼 · 发布于 2024-06-01 08:01:54

你可以使用^{}

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]"}
]

相关问题 更多 >