如何在to_json(Pandas)中包含Dataframe的名称

时间:2017-10-07 16:56:47

标签: python json pandas dataframe

使用此问题的数据集(Pandas dataframe to json without index),如何添加数据框的名称?

to_json()正在回复我:

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

但是我想要这样的JSON:

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

1 个答案:

答案 0 :(得分:3)

IIUC:

In [77]: d = {'stops':df.reset_index().to_dict(orient='records')}

In [78]: js = json.dumps(d, indent=2)

In [79]: print(js)
{
  "stops": [
    {
      "id": 0,
      "location": "[50, 50]"
    },
    {
      "id": 1,
      "location": "[60, 60]"
    },
    {
      "id": 2,
      "location": "[70, 70]"
    },
    {
      "id": 3,
      "location": "[80, 80]"
    }
  ]
}
相关问题