1

I have a list of data frames in Python (3) with boolean values and I want the row-wise AND of the list, but I have no idea how to do it:

d1 = pd.DataFrame({'v' : [True, True, True, True]})
d2 = pd.DataFrame({'v' : [False, True, True, True]})
d3 = pd.DataFrame({'v' : [False, True, False, True]})

dfs = [d1, d2, d3]

What I'd like to have is a data frame with the values [False, True, False, True]. I've tried using a lambda with apply but I have no idea if that's possible with a list of values of which I do not know the size. And I did not see a foldLeft (or similar option) to apply a binary operator on a list of values or DataFrame columns.

Any ideas?

rapidDev
  • 109
  • 2
  • 13
Max Power
  • 952
  • 9
  • 24

1 Answers1

1

Use concat with DataFrame.all for check if all Trues per rows:

print (pd.concat(dfs, axis=1))
      v      v      v
0  True  False  False
1  True   True   True
2  True   True  False
3  True   True   True

print (pd.concat(dfs, axis=1).all(axis=1))
0    False
1     True
2    False
3     True
dtype: bool

Or np.logical_and.reduce with list comprehension:

print (np.logical_and.reduce([x['v'] for x in dfs]))
[False  True False  True]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252