Home > Enterprise >  pandas: filter rows based on two columns
pandas: filter rows based on two columns

Time:12-10

I want to filter rows based on two columns. I am doing this without re-indexing.

This is a small snapshot of the data. The dataframe is called temperatures. I want to filter where city is Lahore or Rome and country is Pakistan or Syria. From this snapshot, I would expect only one row returned -- that is, city is Lahore and country is Pakistan. This is the code. It keeps returning an empty dataframe. It's not the prettiest, but I want to understand why it does not work.

enter image description here

temperatures[((temperatures["country"] == "Pakistan") | (temperatures["country"] == "Syria")) &
             ((temperatures["city"] == "Lahore") | (temperatures["city"] == "Rome"))]

CodePudding user response:

Using .query()

countries = ['Pakistan', 'Syria']
cities = ['Lahore', 'Rome']
temperatures = temperatures.query("country.isin(@countries) | city.isin(@cities)")
  • Related