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?
Use concat
with DataFrame.all
for check if all True
s 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.