【问题标题】:Pandas dataframe to json list format熊猫数据框到 json 列表格式
【发布时间】:2017-08-25 08:50:57
【问题描述】:

我有大熊猫表格数据框可以转换成 JSON。 标准的 .to_json() 函数不会为 JSON 提供紧凑的格式。 如何获得这样的 JSON 输出格式,仅使用 pandas ?

{"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
}

这是一种非常紧凑的 JSON 格式,用于表格数据。 (我可以在行上循环......但是)

【问题讨论】:

    标签: json pandas


    【解决方案1】:

    看来你首先需要to_dict,然后是dictjson

    df = pd.DataFrame({"index": [ 0, 1 ,3 ],
     "col1": [ "250", "1" ,"3" ],
     "col2": [ "250", "1" ,"3" ]
    })
    print (df)
      col1 col2  index
    0  250  250      0
    1    1    1      1
    2    3    3      3
    
    
    print (df.to_dict(orient='list'))
    {'col1': ['250', '1', '3'], 'col2': ['250', '1', '3'], 'index': [0, 1, 3]}
    

    import json
    
    print (json.dumps(df.to_dict(orient='list')))
    {"col1": ["250", "1", "3"], "col2": ["250", "1", "3"], "index": [0, 1, 3]}
    

    因为不是implemented yet

    print (df.to_json(orient='list'))
    

    ValueError:选项“orient”的值“list”无效

    编辑:

    如果索引不是列,则添加reset_index

    df = pd.DataFrame({"col1": [250, 1, 3],
                       "col2": [250, 1, 3]})
    print (df)
       col1  col2
    0   250   250
    1     1     1
    2     3     3
    
    print (df.reset_index().to_dict(orient='list'))
    {'col1': [250, 1, 3], 'index': [0, 1, 2], 'col2': [250, 1, 3]}
    

    【讨论】:

    • 你总是更快;-)
    【解决方案2】:

    您可以使用to_dictjson(如果需要,可以通过assign 添加index 作为额外列):

    import json
    
    df = pd.DataFrame({"col1": [250, 1, 3],
                       "col2": [250, 1, 3]})
    
    json_dict = df.assign(index=df.index).to_dict(orient="list")
    print(json.dumps(json_dict))
    
    >>> '{"index": [0, 1, 2], "col1": [250, 1, 3], "col2": [250, 1, 3]}'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      • 2020-06-03
      • 2022-12-10
      • 1970-01-01
      • 2020-08-03
      相关资源
      最近更新 更多