熊猫数据框到JSON列表格式

Ten*_*sor 5 json pandas

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

{"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
}
Run Code Online (Sandbox Code Playgroud)

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

jez*_*ael 13

看来你to_dict首先需要dict然后json

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]}
Run Code Online (Sandbox Code Playgroud)
import json

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

因为它还没有实现

print (df.to_json(orient='list'))
Run Code Online (Sandbox Code Playgroud)

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]}
Run Code Online (Sandbox Code Playgroud)