Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add conditions to .loc pandas

Assuming that I have a pandas dataframe df I can use .loc() as below:

c1 = df['count'] > 10
c2 = df['min'] > 3
c2 = df['max']> 4

filtered = df.loc[c1 & c2 & c3].T.reset_index()

No say that the conditions are stored in a list:

conditions = [df['count'] > 10, df['min'] > 3, df['max']> 4]

How can I pass this list to the .loc() and indicate that all conditions must hold (&)?

like image 928
Tokyo Avatar asked Dec 23 '22 21:12

Tokyo


2 Answers

You can use functools reduce:

l = [c1,c2,c3]
from functools import reduce
df.loc[reduce(np.logical_and, l)]

@GZ0 improvement...

df.loc[np.logical_and.reduce(l)]
like image 164
Scott Boston Avatar answered Jan 09 '23 18:01

Scott Boston


I think np.logical_and.reduce should work

np.logical_and.reduce(conditions)
like image 36
Andy L. Avatar answered Jan 09 '23 17:01

Andy L.