2016-01-27 4 views
12

パンダでは、2つの他の列のブール演算である計算列を作成したいと考えています。データフレームの2つの列に対する論理演算

パンダでは、2つの数値列を簡単に追加できます。私は論理演算子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)で '&'と '|'を使用する例があります –