pandas 数据框选择多索引中的列 [英] pandas dataframe select columns in multiindex

查看:34
本文介绍了 pandas 数据框选择多索引中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下pd.DataFrame:

I have the following pd.DataFrame:

Name    0                       1                      ...
Col     A           B           A            B         ...
0       0.409511    -0.537108   -0.355529    0.212134  ...
1       -0.332276   -1.087013    0.083684    0.529002  ...
2       1.138159    -0.327212    0.570834    2.337718  ...

它具有带有names=['Name', 'Col']和层次结构级别的MultiIndex列. Name标签从0到n,每个标签都有两个AB列.

It has MultiIndex columns with names=['Name', 'Col'] and hierarchical levels. The Name label goes from 0 to n, and for each label, there are two A and B columns.

我想子选择此DataFrame的所有A(或B)列.

I would like to subselect all the A (or B) columns of this DataFrame.

推荐答案

有一种get_level_values方法,可以将其与布尔索引一起使用以获得预期的结果.

There is a get_level_values method that you can use in conjunction with boolean indexing to get the the intended result.

In [13]:

df = pd.DataFrame(np.random.random((4,4)))
df.columns = pd.MultiIndex.from_product([[1,2],['A','B']])
print df
          1                   2          
          A         B         A         B
0  0.543980  0.628078  0.756941  0.698824
1  0.633005  0.089604  0.198510  0.783556
2  0.662391  0.541182  0.544060  0.059381
3  0.841242  0.634603  0.815334  0.848120
In [14]:

print df.iloc[:, df.columns.get_level_values(1)=='A']
          1         2
          A         A
0  0.543980  0.756941
1  0.633005  0.198510
2  0.662391  0.544060
3  0.841242  0.815334

这篇关于 pandas 数据框选择多索引中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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