1

I would like to make a boolean vector that is created by the comparison of two input boolean vectors. I can use a for loop, but is there a better way to do this?

My ideal solution would look like this:

df['A'] = [True, False, False, True]
df['B'] = [True, False, False, False]
C = ((df['A']==True) or (df['B']==True)).as_matrix()
print C

>>> True, False, False, True
Krumelur
  • 31,081
  • 7
  • 77
  • 119
user3155053
  • 2,005
  • 2
  • 16
  • 16

2 Answers2

4

I think this is what you are looking for:

C = (df['A']) | (df['B'])
C

0     True
1    False
2    False
3     True
dtype: bool

You could then leave this as a series or convert it to a list or array

johnchase
  • 13,155
  • 6
  • 38
  • 64
  • Got it! The link goes deeper into your solution: http://stackoverflow.com/questions/3845018/python-boolean-operators-vs-bitwise-operators – user3155053 Jan 04 '16 at 20:19
4

Alternatively you could use any method with axis=1 to search in index. It also will work for any number of columns where you have True values:

In [1105]: df
Out[1105]: 
       B      A
0   True   True
1  False  False
2  False  False
3  False   True

In [1106]: df.any(axis=1)
Out[1106]: 
0     True
1    False
2    False
3     True
dtype: bool
Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93