在转换为具有拆分方向的json之前,请从dataframe中删除索引

2024-05-05 08:43:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下命令将pandas数据帧输出到json对象:

df_as_json = df.to_json(orient='split')

json对象中存储了多余的索引。我不想包括这些。在

我试着移除它们

^{pr2}$

但是我得到了

AttributeError: 'str' object has no attribute 'to_json'

是否有一种快速的方法来重新组织dataframe,使其在.to\u json(orient='split')调用期间或之前不包含单独的索引列?在


Tags: to数据对象命令jsonpandasdfobject
2条回答
  • 使用to_json(orient='split')转换为json
  • 使用json模块将该字符串加载到字典中
  • del json_dict['index']删除{}键
  • 使用json.dumpjson.dumps将字典转换回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]]}'

Since two years backpandas>= 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/api/pandas.DataFrame.to_json.html

相关问题 更多 >