从多索引 pandas 中选择 [英] selecting from multi-index pandas
本文介绍了从多索引 pandas 中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含列"A"和"B"的多索引数据框.
I have a multi-index data frame with columns 'A' and 'B'.
是否可以通过在多索引的一列上进行过滤而不选择将索引重置为单列索引的方式来选择行?
Is there is a way to select rows by filtering on one column of the multi-index without resetting the index to a single column index?
例如.
# has multi-index (A,B)
df
#can I do this? I know this doesn't work because the index is multi-index so I need to specify a tuple
df.ix[df.A ==1]
推荐答案
一种方法是使用get_level_values
索引方法:
One way is to use the get_level_values
Index method:
In [11]: df
Out[11]:
0
A B
1 4 1
2 5 2
3 6 3
In [12]: df.iloc[df.index.get_level_values('A') == 1]
Out[12]:
0
A B
1 4 1
在0.13中,您可以使用 xs
和drop_level
参数:
In 0.13 you'll be able to use xs
with drop_level
argument:
df.xs(1, level='A', drop_level=False) # axis=1 if columns
注意:如果这是列MultiIndex而不是索引,则可以使用相同的技术:
Note: if this were column MultiIndex rather than index, you could use the same technique:
In [21]: df1 = df.T
In [22]: df1.iloc[:, df1.columns.get_level_values('A') == 1]
Out[22]:
A 1
B 4
0 1
这篇关于从多索引 pandas 中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文