Issue while using query in python

Viewed 39

Here is my data

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

I would like to input data to be filtered using i via pandas query.

While this works-

    i = 'Honda Civic'
   df[df['Brand'] == i]

While, if I try do it via query as shown below, it doesn't work -

i = 'Honda Civic'
(df
.query('Brand' == i))

How should I modify the query command to make it work?

1 Answers

I always prefer:

df[df['Brand'] == i]

This is much easier for me, and I try to avoid the "query" method of Pandas DataFrames. Especially since you can expand on the resulting DataFrame slice. For example, if you had other columns such as "State" and "Price", you could groupby + aggregate like so:

df[df['Brand'] == i].groupby('State')['Price'].sum()
Related