Pandas DataFrame : How to select rows on multiple conditions?

Viewed 8830

I'm trying to select rows of a DataFrame based on a list of conditions that needs to be all satisfied. Those conditions are stored in a dictionary and are of the form {column: max-value}.

This is an example: dict = {'name': 4.0, 'sex': 0.0, 'city': 2, 'age': 3.0}

I need to select all DataFrame rows where the corresponding attribute is less than or equal to the corresponding value in the dictionary.

I know that for selecting rows based on two or more conditions I can write:

rows = df[(df[column1] <= dict[column1]) & (df[column2] <= dict[column2])]

My question is, how can I select rows that matches the conditions present in a dictionary in a Pythonic way? I tried this way,

keys = dict.keys() 
rows = df[(df[kk] <= dict[kk]) for kk in keys]

but it gives me an error = "[ expected" that doesn't disappear even putting the [ symbol.

3 Answers
Related