在以分裂方向转换为JSON之前,请从数据框架中删除索引



我使用以下内容将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
  • 使用json模块将该字符串加载到字典
  • del json_dict['index']删除index
  • 使用json.dumpjson.dumps
  • 将字典转换回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

最新更新