Reputation: 7022
I have a pandas series of booleans and was wondering what the best way is to apply "or" or "and" to the whole series. I am thinking something along the lines of a Haskell
fold
From my understanding, the pandas
.apply
will apply a function to each element in the series so doesn't seem to do what I need.
Thanks, Anne
Upvotes: 3
Views: 412
Reputation: 548
To get True
if the 1st AND ALL other elements of a series are True
, we can use the all
method, like this:
import pandas as pd
pd.Series([False, False, False]).all()
# False
pd.Series([False, False, True]).all()
# False
pd.Series([True, True, True]).all()
# True
To get True
if the 1st OR ANY other element of a series is True
, we can use the any
method, like this:
pd.Series([False, False, False]).any()
# False
pd.Series([False, False, True]).any()
# True
pd.Series([True, True, True]).any()
# True
PS: be aware of the behavior for series which do not contain (only) boolean values:
pd.Series([]).all()
# True
pd.Series([True, True, 1.0]).all()
# 1.0
pd.Series([True, True, 'foobar']).all()
# 'foobar'
pd.Series(['Non empty', 'strings are', 'truthy']).all()
# 'truthy'
and
pd.Series([]).any()
# False
pd.Series([False, False, 0.0]).any()
# 0.0
pd.Series([False, False, '']).any()
# ''
pd.Series([False, '', '<-- the empty string is "falsy"']).any()
# '<-- the empty string is "falsy"'
Upvotes: 1