为了账号安全,请及时绑定邮箱和手机立即绑定

熊猫:从多级列索引中删除一个级别?

熊猫:从多级列索引中删除一个级别?

慕勒3428872 2019-09-19 16:35:39
如果我有一个多级列索引:>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])>>> pd.DataFrame([[1,2], [3,4]], columns=cols)    一种   --- +  -     b | C-  +  -  +  - 0 | 1 | 21 | 3 | 4如何删除该索引的“a”级别,因此我最终得到:    b | C-  +  -  +  - 0 | 1 | 21 | 3 | 4
查看完整描述

3 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

你可以使用MultiIndex.droplevel:


>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])

>>> df = pd.DataFrame([[1,2], [3,4]], columns=cols)

>>> df

   a   

   b  c

0  1  2

1  3  4


[2 rows x 2 columns]

>>> df.columns = df.columns.droplevel()

>>> df

   b  c

0  1  2

1  3  4


[2 rows x 2 columns]


查看完整回答
反对 回复 2019-09-19
?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

删除索引的另一种方法是使用列表解析:


df.columns = [col[1] for col in df.columns]


   b  c

0  1  2

1  3  4

如果要组合两个级别的名称(如下面的示例中底层包含两个'y'),此策略也很有用:


cols = pd.MultiIndex.from_tuples([("A", "x"), ("A", "y"), ("B", "y")])

df = pd.DataFrame([[1,2, 8 ], [3,4, 9]], columns=cols)


   A     B

   x  y  y

0  1  2  8

1  3  4  9

删除顶级会留下两列,索引为“y”。通过将名称与列表理解相结合可以避免这种情况。


df.columns = ['_'.join(col) for col in df.columns]


    A_x A_y B_y

0   1   2   8

1   3   4   9

这是我在做一个小组后遇到的问题,并且花了一段时间才找到解决它的另一个问题。我在这里针对具体案例调整了解决方案。


查看完整回答
反对 回复 2019-09-19
?
GCT1015

TA贡献1827条经验 获得超4个赞

另一种方法是使用.xs方法df根据横截面重新分配。df


>>> df


    a

    b   c

0   1   2

1   3   4


>>> df = df.xs('a', axis=1, drop_level=True)


    # 'a' : key on which to get cross section

    # axis=1 : get cross section of column

    # drop_level=True : returns cross section without the multilevel index


>>> df


    b   c

0   1   2

1   3   4


查看完整回答
反对 回复 2019-09-19
  • 3 回答
  • 0 关注
  • 868 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信