熊猫:获得系列多指数水平

A U*_*ser 11 python multi-index pandas

我有一个包含多个级别的数据框,例如:

idx = pd.MultiIndex.from_product((['foo', 'bar'], ['one', 'five', 'three' 'four']),
                                 names=['first', 'second'])
df = pd.DataFrame({'A': [np.nan, 12, np.nan, 11, 16, 12, 11, np.nan]}, index=idx).dropna().astype(int)

              A     
first second
foo   five     12
      four     11
bar   one      16
      five     12
      three    11
Run Code Online (Sandbox Code Playgroud)

我想使用标题为索引级别创建一个新列second,以便我得到

              A    B  
first second
foo   five     12   five
      four     11   four
bar   one      16   one
      five     12   five
      three    11   three
Run Code Online (Sandbox Code Playgroud)

我可以通过重置索引,复制列,然后重新应用来做到这一点,但这似乎更圆.

我试过了df.index.levels[1],但是创建了一个排序列表,它不保留顺序.

如果它是单个索引,我会使用df.index但在多索引中创建一列元组.

如果这在其他地方得到解决,请分享,因为我没有运气搜索stackoverflow档案.

Ale*_*der 13

df['B'] = df.index.get_level_values(level=1)  # Zero based indexing.
# df['B'] = df.index.get_level_values(level='second')  # This also works.
>>> df
               A      B
first second           
foo   one     12    one
      two     11    two
bar   one     16    one
      two     12    two
      three   11  three
Run Code Online (Sandbox Code Playgroud)