【问题标题】:How to include Dataframe's name on to_json (Pandas)如何在 to_json (Pandas) 上包含 Dataframe 的名称
【发布时间】:2018-03-19 06:25:39
【问题描述】:

使用本题的数据集(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]"}
]
}

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 1970-01-01
      • 2013-06-10
      • 2013-10-04
      • 2015-10-22
      • 2015-07-25
      • 1970-01-01
      相关资源
      最近更新 更多