小编典典

熊猫数据框到JSON列表格式

json

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

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

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


阅读 252

收藏
2020-07-27

共1个答案

小编典典

看来你需要to_dictdictjson

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

由于尚未实现

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

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

编辑:

如果index不是column,请添加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]}
2020-07-27