gpt4 book ai didi

python - Pandas 数据框问题 : `reset_index` does not remove hierarchical index

转载 作者:太空宇宙 更新时间:2023-11-03 14:41:39 27 4
gpt4 key购买 nike

我正在尝试展平 Pandas Dataframe MultiIndex,以便只有一个级别的索引。基于任意数量的 SE 帖子的通常解决方案是使用 df.reset_index 命令,但这并不能解决问题。

我从 Xarray DataArray 开始并将其转换为数据帧。原始数据框如下所示。

                results
simdata a_ss_yr attr attr1 attr2 attr3
run year
0 0 0 0 0 0 0
1 1 6 2 0 4
2 2 4 2 2 0
3 3 1 0 0 1
4 4 2 0 2 0

为了压平我使用的索引

df.reset_index(drop=True)

这只完成了这个:

         run    year  results
simdata a_ss_yr attr attr1 attr2
0 0 0 0 0 0 0
1 0 1 1 6 2 0
2 0 2 2 4 2 2
3 0 3 3 1 0 0
4 0 4 4 2 0 2

我不止一次尝试执行 df.reset_index() 选项,但这仍然没有使索引变平,我只想将其设置为单级索引。

更具体地说,我需要将“run”和“year”变量转到 0 级列名集,并且我需要完全删除“result”标题。

我一直在阅读 Pandas 文档,但似乎并没有真正描述对索引进行这种手术。有谁知道如何做到这一点?

最佳答案

先用droplevel用于删除第一级 MultiIndex 然后是 reset_index :

df.columns = df.columns.droplevel(0)
df = df.reset_index()

关于python - Pandas 数据框问题 : `reset_index` does not remove hierarchical index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52774232/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com