【问题标题】:pandas reset_index of certain level removes entire level of multiindex某个级别的 pandas reset_index 删除整个级别的多索引
【发布时间】:2022-01-26 13:30:15
【问题描述】:

我有这样的 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

我失去了整个第二级索引!为什么?我认为每个“集群”都是 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 在某个级别上只是删除它?这是主要问题!

【问题讨论】:

    标签: pandas date indexing


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 2018-08-03
      • 2023-04-02
      • 2021-01-28
      • 2018-07-09
      • 1970-01-01
      • 2010-12-13
      相关资源
      最近更新 更多