2012-04-16 47 views
15

特定级别选择数据我有以下的熊猫数据框用多指标(Z,A):在从多指标

   H1  H2 
    Z A 
0 100 200 0.3112 -0.4197 
1 100 201 0.2967 0.4893  
2 100 202 0.3084 -0.4873 
3 100 203 0.3069 NaN   
4 101 203 -0.4956 NaN  

问:我如何选择与A = 203的所有项目?我试过df[:,'A']但它不起作用。然后我发现this联机文档中,所以我尝试:
df.xs(203,level='A')
但我得到:
TypeError: xs() got an unexpected keyword argument 'level'
我也没有看到在安装文档(df.xs?)这个参数:
“参数---- ------ key:object一些包含在索引中的标签,或者部分包含在MultiIndex轴中:int,default 0用于检索副本上的横截面的轴:布尔值,默认为True是否复制数据“
注:我有开发版本。我发现this thread。他们建议是这样的:

df.select(lambda x: x[1]==200, axis=0) 

我还是想知道与水平参数,或者什么是在当前版本的推荐方法df.xs发生了什么事。

+0

哪个版本您使用的?显然'level'是在[version 0.7.0']处添加的(http://pandas.pydata.org/pandas-docs/dev/whatsnew.html#v-0-7-0-february-9-2012) 。 – Avaris 2012-04-16 13:44:34

+0

很明显,这就是问题所在,我在0.6.1上,我是从git安装的,但是我仍然在0.6.1上,谢谢,我应该关闭这个问题,如果是的话,怎么办? – elyase 2012-04-16 14:01:12

+0

你可以用问题的原因和替代解决方案写出答案并接受它。 – Avaris 2012-04-16 14:05:10

回答

7

问题就出在我的假设(不正确的),我是在开发的版本,而在现实中我有1.6.1,可以检查与当前安装的版本:在当前版本df.xs()

import pandas 
print pandas.__version__ 

与水平参数工作正常。

4

不是直接这个问题的答案,但如果你要选择一个以上的价值,你可以使用“切片()”标记:

import numpy 
from pandas import MultiIndex, Series 

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], 
       ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] 
tuples = list(zip(*arrays)) 
index = MultiIndex.from_tuples(tuples, names=['first', 'second']) 
s = Series(numpy.random.randn(8), index=index) 

In [10]: s 
Out[10]: 
first second 
bar one  0.181621 
     two  1.016225 
baz one  0.716589 
     two  -0.353731 
foo one  -0.326301 
     two  1.009143 
qux one  0.098225 
     two  -1.087523 
dtype: float64 

In [11]: s.loc[slice(None)] 
Out[11]: 
first second 
bar one  0.181621 
     two  1.016225 
baz one  0.716589 
     two  -0.353731 
foo one  -0.326301 
     two  1.009143 
qux one  0.098225 
     two  -1.087523 
dtype: float64 

In [12]: s.loc[slice(None), "one"] 
Out[12]: 
first 
bar  0.181621 
baz  0.716589 
foo  -0.326301 
qux  0.098225 
dtype: float64 

In [13]: s.loc["bar", slice(None)] 
Out[13]: 
first second 
bar one  0.181621 
     two  1.016225 
dtype: float64