pandas reset_index 某个级别删除整个级别的 multiindex

pandas reset_index of certain level removes entire level of multiindex

我有这样的 DataFrame:

                          performance
year      month     week
2015      1         2     4.170358
                    3     3.423766
                    4    -1.835888
                    5     8.157457
          2         6    -3.276887
...                            ...
2018      7         30   -1.045241
                    31   -0.870845
          8         31    0.950555
                    32    6.757876
                    33   -2.203334

我希望周数在范围 (0 或 1,n) 内,其中 n = 当前年月的周数。

好吧,我认为最简单的方法是使用

df.reset_index(level=2, drop=True)

但后来我意识到这是错误的,在最好的情况下我会得到

                          performance
year      month     week
2015      1         0     4.170358
                    1     3.423766
                    2    -1.835888
                    3     8.157457
          2         4    -3.276887
...                            ...
2018      7         n-4  -1.045241
                    n-3  -0.870845
          8         n-2   0.950555
                    n-1   6.757876
                    n    -2.203334

但是在我这样做之后,我得到了一个意想不到的行为

                        close
timestamp timestamp
2015      1          4.170358
          1          3.423766
          1         -1.835888
          1          8.157457
          2         -3.276887
...                       ...
2018      7         -1.045241
          7         -0.870845
          8          0.950555
          8          6.757876
          8         -2.203334

我丢失了整个二级索引!为什么?我以为每个 'cluster' 都是 0 到 n (是的,这是错误的,我如上所述意识到了)... 我解决了类似的问题

df.groupby(level = [0, 1]).apply(lambda x: x.reset_index(drop=True))

并得到了我想要的 DataFrame 形式:

                 performance
year month
2015 1     0  4.170358
           1  3.423766
           2 -1.835888
           3  8.157457
     2     0 -3.276887
...                ...
2018 7     3 -1.045241
           4 -0.870845
     8     0  0.950555
           1  6.757876
           2 -2.203334

但是为什么?为什么 reset_index 在某个级别会掉落它?这是主要问题!

当您重置整个索引时,

reset_indexdrop=True 添加默认索引 。如果您只重置多级索引的一个级别,它只会将其删除。