Home > Net >  Python Pandas combine multiple boolean series
Python Pandas combine multiple boolean series

Time:06-22

I have a dataframe with multiple columns such as below

gender marital education
male single tertiary

I have a list of requirements that contain boolean series and I need to combine them all using & sign.

bool_gender = df["gender"] == "male"
bool_marital = df["marital"] == "married"
bool_education = df["education"] == "secondary"
[bool_gender, bool_marital, bool_education]

How can I combine all of the items in the list using functional programming in Python 3 to obtain a single boolean value that is the result of the following expression:

desired output = bool_gender & bool_marital & bool_education


Possible use: 

reduce("&", map(function, iter))


CodePudding user response:

you could do something like this with the operator module and functools.reduce function:

>>> import operator
>>> from functools import reduce
>>> lst = [True, True, False]
>>> reduce(operator.and_,lst)
False 

CodePudding user response:

You can use the reduce version of numpy.bitwise_and:

np.bitwise_and.reduce([bool_gender, bool_marital, bool_education])
  • Related