从数据帧中删除索引,然后再以拆分方向转换为json

pro*_*uri 5 python json dataframe pandas

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

df_as_json = df.to_json(orient='split')
Run Code Online (Sandbox Code Playgroud)

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

为了删除它们,我尝试了

df_no_index = df.to_json(orient='records')
df_as_json = df_no_index.to_json(orient='split')
Run Code Online (Sandbox Code Playgroud)

但是我得到了

AttributeError: 'str' object has no attribute 'to_json'
Run Code Online (Sandbox Code Playgroud)

有没有一种快速的方法来重组数据框,以便在.to_json(orient ='split')调用期间或之前不包含单独的索引列?

piR*_*red 7

  • 转换为jsonto_json(orient='split')
  • 使用json模块将该字符串加载到字典中
  • 删除index密钥del json_dict['index']
  • 将字典转换回jsonwithjson.dumpjson.dumps

演示

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


Mic*_*ico 5

自从两年前 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]]}'
Run Code Online (Sandbox Code Playgroud)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html