重新索引Pandas MultiIndex的特定级别

5

我有一个带有3个索引级别的DataFrame,我需要重新索引第三个级别而不改变第一和第二个级别。

我的DataFrame如下:

tuples = [('A', 'a', 1), ('A', 'a', 3), ('A', 'b', 3), ('B', 'c', 1), ('B', 'c', 2), ('B', 'c', 3), ('C', 'd', 2)]

idx = pd.MultiIndex.from_tuples(tuples, names=['first', 'second', 'third'])

df = pd.DataFrame(np.random.randn(7, 2), index=idx, columns=['col1', 'col2'])

                        col1      col2
first second third                    
A     a      1     -0.999816 -0.599815
             3     -0.277794 -0.453870
      b      3      1.116561  0.760010
B     c      1      1.018475 -0.667625
             2      0.695997  0.641531
             3      0.593724  0.265256
C     d      2      1.133767  0.716083

我希望得到一个这样的 DataFrame:

                        col1      col2
first second third                    
A     a      1     -0.999816 -0.599815
             2      0         0
             3     -0.277794 -0.453870
      b      1      0         0
             2      0         0
             3      1.116561  0.760010
B     c      1      1.018475 -0.667625
             2      0.695997  0.641531
             3      0.593724  0.265256
C     d      1      0         0
             2      1.133767  0.716083
             3      0         0

我希望第三个索引在任何地方都相同。
1个回答

5
使用 DataFrame.unstack 默认按照 MultiIndex 的最后一层进行操作,使用 DataFrame.stack 函数进行逆操作:
df1 = df.unstack(fill_value=0).stack()
print (df1)
                        col1      col2
first second third                    
A     a      1     -1.549363 -1.206828
             2      0.000000  0.000000
             3      0.445008 -0.173086
      b      1      0.000000  0.000000
             2      0.000000  0.000000
             3      1.488947 -0.792520
B     c      1      1.838997 -0.439362
             2      1.160003 -0.577093
             3     -1.031044 -0.838885
C     d      1      0.000000  0.000000
             2      0.316934  0.353254
             3      0.000000  0.000000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接