之前或之前不包含单独的索引列
我使用以下内容将pandas dataframe输出到JSON对象:
df_as_json = df.to_json(orient='split')
在JSON对象中存储了多余索引。我不想包括这些。
要删除它们,我尝试了
df_no_index = df.to_json(orient='records')
df_as_json = df_no_index.to_json(orient='split')
但是我得到了
AttributeError: 'str' object has no attribute 'to_json'
是否有快速重组数据框的方法,因此在.to_json(orient ='split'(呼叫?
- 导入JSON模块
- 用
to_json(orient='split')
转换为 - 使用
json
模块将该字符串加载到字典 - 用
del json_dict['index']
删除index
键 - 使用
json.dump
或json.dumps
将字典转换回
json
json
demo
import json
df = pd.DataFrame([[1, 2], [3, 4]], ['x', 'y'], ['a', 'b'])
json_dict = json.loads(df.to_json(orient='split'))
del json_dict['index']
json.dumps(json_dict)
'{"columns": ["a", "b"], "data": [[1, 2], [3, 4]]}'
自两年后pandas
(> = = V0.23.0(提供index
参数(仅适用于orient='split'
和orient='table'
(:
df = pd.DataFrame([[1, 2], [3, 4]], ['x', 'y'], ['a', 'b'])
df.to_json(orient='split', index=True)
# '{"columns":["a","b"],"index":["x","y"],"data":[[1,2],[3,4]]}'
df.to_json(orient='split', index=False)
# '{"columns":["a","b"],"data":[[1,2],[3,4]]}'
https://pandas.pydata.org/pandas-docs/stable/reference/PANDAS.DATAFRAME.TO_JSON.HTML