Hugo Wolf
Hugo Wolf

Reputation: 59

python dataframe filtering combination of or and and

I'm trying to filter a dataframe based on the following condition:

colA = alpha OR beta

colB = gamma

I've tried the following

filtered_df = (df[(df['colA'] == 'alpha') & (df['colB'] == 'gamma')]) | (df[(df['colA'] == 'beta') & (df['colB'] == 'gamma')])

But this doesn't work and I get the following error message :

TypeError: unsupported operand type(s) for |: 'str' and 'bool'

What would be the most pythonic way to achieve the desired outcome?

Thanks!

Upvotes: 1

Views: 753

Answers (2)

George
George

Reputation: 151

You can try something like this.

df.loc[((df['colA'] == 'alpha') | (df['colA'] == 'beta')) & (df['colB'] == 'gamma')]

Upvotes: 1

Anurag Dabas
Anurag Dabas

Reputation: 24314

You can use try loc+isin()+eq():

filtered_df =df.loc[(df['colA'].isin(['alpha','beta'])) & (df['colB'].eq('gamma'))]

Now If you print filtered_df you will get your filtered dataframe

Upvotes: 3

Related Questions