Skip to content Skip to sidebar Skip to footer

How To Make An "and" Operation In Pandas Dataframe With Items In A List

For example, I have lists of column names, the equal relations and conditions column = ['height', 'age', 'gender'] equal = ['>', '>', '=='] condition = [1.68, 20, 'F'] And I

Solution 1:

I think need query for built conditions, but is necessary if-else condition for add "" for strings values in values:

df = pd.DataFrame({'gender':list('MMMFFF'),
                   'height':[4,5,4,5,5,4],
                   'age':[70,80,90,40,2,3]})

print (df)
  gender  height  age
0      M       4701      M       5802      M       4903      F       5404      F       525      F       43

q = ' & '.join(['{}{}"{}"'.format(i,j,k) ifisinstance(k, str) 
               else'{}{}{}'.format(i,j,k) for i, j, k inzip(column, equal, condition)])
print (q)
height>1.68 & age>20 & gender=="F"

Thank you @Yakym Pirozhenko for simplier solution:

q = ' & '.join(['{}{}{}'.format(i,j,repr(k)) for i, j, k inzip(column, equal, condition)])
print (q)
height>1.68 & age>20 & gender=='F'

df = df.query(q)
print (df)
  gender  height  age
3      F       5   40

Post a Comment for "How To Make An "and" Operation In Pandas Dataframe With Items In A List"