2

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")]
Rishab Gupta
  • 561
  • 3
  • 17
  • Possible duplicate of [Select rows from a DataFrame based on values in a column in pandas](https://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas) – help-ukraine-now Aug 13 '19 at 17:54

1 Answers1

2

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
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55