2013-06-20 113 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