Pandas dataframe to json list format

后端 未结 2 903
不思量自难忘°
不思量自难忘° 2020-12-17 20:51

I have large pandas tabular dataframe to convert into JSON. The standard .to_json() functions does not make a compact format for JSON. How to get JSON output forma like this

2条回答
  •  既然无缘
    2020-12-17 21:44

    You can use to_dict and json (and add the index as extra column if required via assign):

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

提交回复
热议问题