3

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?

5
  • Tried this (df .query('Brand' == @i) - doesnt work Commented Aug 24, 2020 at 21:10
  • 2
    my bad: df.query("Brand==@i") remove the quotes around Brand Commented Aug 24, 2020 at 21:12
  • This is my code i = ['Honda Civic'] (df. query(Brand==@i)) . I still get invalid syntax error :( Commented Aug 24, 2020 at 21:14
  • 2
    I just made an edit. Have a look at previous comment. df.query("Brand==@i"). and no need to wrap it in a list, if it is just one item. Commented Aug 24, 2020 at 21:14
  • 1
    done, works now Commented Aug 24, 2020 at 21:16

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.