Jordan
Jordan

Reputation: 1495

Why is filtering with multiple conditions not working?

I need to filter my DataFrame based on two conditions. I need to filter out any observation where cause = 'fire' AND the flag = 1. It can be fire and flag = 0. It can be flag = 1 and cause != 'fire'. Just not both at the same time.

I tried the following:

 df.loc[(df['flag'] != 1) & (df['cause'] != 'Fire')]

But this gets rid of all 1s and/or fire. I need both conditions to be met to be filtered out. Not sure where I'm going wrong.

Upvotes: 1

Views: 397

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31166

built a DF with contents you defined. Make sure you code your logic. You state NOT(cause=="Fire" AND flag==1)

import random
c = ["Fire","Water"]
df = pd.DataFrame({"flag":[random.randint(0,1) for r in range(10)], "cause":[c[random.randint(0,1)] for r in range(10)]})

df.loc[~((df['flag'] == 1) & (df['cause'] == 'Fire'))]

Upvotes: 1

Related Questions