pythonpandasfiltering

Filter Multiple Values using pandas


I am using Python and Pandas. I have a df that works similar to this:

 +--------+--------+-------+
 |  Col1  |  Col2  | Col3 |
 +--------+--------+-------+
 | Team 1 | High   | Pizza |
 | Team 1 | Medium | Sauce |
 | Team 1 | Low    | Crust |
 +--------+--------+-------+

I would like to filter the df so that I only see High or Medium from Col2.

This is what I have tried with no luck

 df = df.loc[df['Col2'] == 'High' | (df['Col2'] == 'Medium')]

This is the error I am getting

 cannot compare a dtyped [bool] array with a scalar of type [bool]

Any ideas how to make this work and what that error means?


Solution

  • You are missing a pair of parentheses to get comparable items on both sides of the | operator - which has higher precedence than ==:

    df = df.loc[(df['Col 2'] == 'High') | (df['Col2'] == 'Medium')]