pandas 数据框到JSON列表格式 [英] Pandas dataframe to json list format

查看:83
本文介绍了 pandas 数据框到JSON列表格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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, using pandas only ?

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

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

This is a much compact format form of JSON for tabular data. (I can do a loop over the rows.... but)

推荐答案

似乎您需要


import json

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

因为它不是已实现:

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

ValueError:选项东方"的无效值列表"

ValueError: Invalid value 'list' for option 'orient'

如果索引不是列,请添加 reset_index :

If index is not column, add 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]}

这篇关于 pandas 数据框到JSON列表格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆