Rishab Gupta
Rishab Gupta

Reputation: 581

Filter a dataframe with NOT and AND condition

I know this question has been asked multiple times, but for some reason it is not working for my case.

So I want to filter the dataframe using the NOT and AND condition. For example, my dataframe df looks like:

col1    col2
a       1
a       2
b       3
b       4
b       5
c       6

Now, I want to use a condition to remove where col1 has "a" AND col2 has 2 My resulting dataframe should look like:

col1    col2
a       1
b       3
b       4
b       5
c       6

I tried this: Even though I used & but it removes all the rows which have "a" in col1 .

df = df[(df['col1'] != "a") & (df['col2'] != "2")]

Upvotes: 2

Views: 481

Answers (2)

G.G
G.G

Reputation: 765

df1.query("not (col1=='a' and col2==2)")

Upvotes: 0

Djaouad
Djaouad

Reputation: 22776

To remove cells where col1 is "a" AND col2 is 2 means to keep cells where col1 isn't "a" OR col2 isn't 2 (negation of A AND B is NOT(A) OR NOT(B)):

df = df[(df['col1'] != "a") | (df['col2'] != 2)]   #   or "2", depending on whether the `2` is an int or a str

Upvotes: 2

Related Questions