2016-01-27 106 views
12

在熊貓中,我想創建一個計算列,這是另外兩列的布爾操作。在數據框的兩列上進行邏輯運算

在熊貓中,很容易將兩個數字列相加。我想用邏輯運算符AND做類似的事情。這是我的第一次嘗試:

In [1]: d = pandas.DataFrame([{'foo':True, 'bar':True}, {'foo':True, 'bar':False}, {'foo':False, 'bar':False}]) 

In [2]: d 
Out[2]: 
    bar foo 
0 True True 
1 False True 
2 False False 

In [3]: d.bar and d.foo ## can't 
... 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

所以我想邏輯運算符不像熊貓的數字運算符那樣工作。我試圖做的錯誤信息顯示什麼,並使用bool()

In [258]: d.bar.bool() and d.foo.bool() ## spoiler: this doesn't work either 
... 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

我發現,通過鑄造布爾列int,加在一起,評估爲布爾工作的方式。

In [4]: (d.bar.apply(int) + d.foo.apply(int)) > 0 ## Logical OR 
Out[4]: 
0  True 
1  True 
2 False 
dtype: bool 

In [5]: (d.bar.apply(int) + d.foo.apply(int)) > 1 ## Logical AND 
Out[5]: 
0  True 
1 False 
2 False 
dtype: bool 

這是錯綜複雜的。有沒有更好的辦法?

回答

18

是的,還有更好的辦法!只需使用&元素邏輯和運算符:

d.bar & d.foo 

0  True 
1 False 
2 False 
dtype: bool 
+2

謝謝!熊貓文檔中提到了這個嗎? – dinosaur

+2

@dinosaur是的,在[布爾索引部分]中有使用'&'和'|'的示例(http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing) –