基于多个一级列的子集多索引DataFrame [英] Subset multi-indexed DataFrame based on multiple level 1 columns

查看:0
本文介绍了基于多个一级列的子集多索引DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多=索引的DataFrame,但我希望每个级别1只保留两列,用于每个级别0变量(即列‘1’和‘2’)。我可以单独设置它们的子集,但我想一起设置子集,这样我就可以并排保留这些值

这是DataFrame

index = pd.MultiIndex.from_tuples(list(zip(*[['bar1', 'foo1', 'bar1', 'foo2','bar3','foo3'], ['one','two','three','two','one','four']])))
df = pd.DataFrame(np.random.randn(2, 6), columns=index)

以下是为级别1中的一列设置子集的方法

df.iloc[:, df.columns.get_level_values(1)== 'one']
# or 
df.xs('one', level=1, axis=1)

# but adding two columns within either command will not work e.g. 
df.xs(('one','two), level=1, axis=1)

这将是预期的输出

         bar1        foo1       foo2         bar3
          one         two        two          one
0   -0.508272   -0.195379   0.865563     2.002205
1   -0.771565    1.360479   1.900931    -1.589277

推荐答案

以下是使用pd.IndexSlice的一种方法:

idnx = pd.IndexSlice[:, ['one', 'two']]
df.loc[:, idnx]

输出:

       bar1      bar3      foo1      foo2
        one       one       two       two
0  0.589999  0.261224 -0.106588 -2.309628
1  0.646201 -0.491110  0.430724  1.027424

另一种使用pd.DataFrame.loc的小参数axis的方法:

df.loc(axis=1)[:, ['one', 'two']]

输出:

       bar1      bar3      foo1      foo2
        one       one       two       two
0  0.589999  0.261224 -0.106588 -2.309628
1  0.646201 -0.491110  0.430724  1.027424

注意:pd.DataFrame.loc的文档API中没有列出此参数,但在Using Slicers段落中关于中途向下的Using Slicers段落中引用了此参数。

这篇关于基于多个一级列的子集多索引DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆