Creating a pandas series for indexing from a list of pd.series while adding logical operators

34 Views Asked by At

I create a list containing several pandas series which act as indexing conditions. Later, I want to put these together and separate them by a logical or operator. I wonder if there is a more elegant way to do this, specially for the last part.

Currently, I have:

cond_list = []
for a in df1.var1.unique():
    b_set = df1[df1['a'] == a].b.unique()
    c = ((df2[a].str.contains(a)) & 
         (df2[b].isin(b_set))
        )
    cond_list.append(c)

which is followed by:

cond = (cond_list[0] | cond_list[1] | cond_list[2] | cond_list[3] | cond_list[4] | cond_list[5] | cond_list[6] | cond_list[7] | cond_list[8] | cond_list[9] | cond_list[10])

How could I use list comprehension to make the last part more efficient/elegant? I tried:

cond = tuple(for c in cond_list)

but this misses the | operator and I don't know how to add it (and it's also a tuple). Any hints welcome!

1

There are 1 best solutions below

0
Oliver On

If you want to evaluate if there is any True value in the tuples you could do:

cond = any(cond_list)

If you instead want to do and operations try:

cond = all(cond_list)