2013-06-20 115 views
19

布尔索引尽管有是如何索引Python的pandas库中的数据帧,我仍然无法制定出SELECT一个优雅的方式荷兰国际集团上多列至少twogood教程。Python的大熊猫:上多列

>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) 
>>> d 
    x y 
0 1 4 
1 2 5 
2 3 6 
3 4 7 
4 5 8 
>>> d[d['x']>2] # This works fine 
    x y 
2 3 6 
3 4 7 
4 5 8 
>>> d[d['x']>2 & d['y']>7] # I had expected this to work, but it doesn't 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 

我发现(我认为是什么)做的一个相当不雅的方式,这样

>>> d[d['x']>2][d['y']>7] 

但它并不漂亮,而且它的分数相当低的可读性(我认为)。

有没有更好的Python方法?

回答

50

这是一个优先运算符问题。

您应该添加额外的括号,使您的多工况试验工作:

d[(d['x']>2) & (d['y']>7)] 

你提到的教程This section显示均采用与几个布尔条件和括号的例子。

1

仍有可能是一个更好的办法,但

In [56]: d[d['x'] > 2] and d[d['y'] > 7] 
Out[56]: 
    x y 
4 5 8 

作品。

+1

这个工作,但最终使用python操作符(而不是numpy),所以会慢得多 – Jeff

+0

这是一个很好的解决方案。我喜欢它明确使用'和'的事实。更清楚地表明有两个条件被评估。 – LondonRob

+0

哦,我刚刚发现这个问题[重复](http://stackoverflow.com/questions/8916302/selecting-across-multiple-columns-with-python-pandas)。哎呦。 – LondonRob