2

I have a dataframe and I want to delete all rows where column A is equal to blue and also col B is equal to green.

I though the below should work, but its not the case.

Can anyone see the problem

df=df.loc[~(df['A']=='blue' & df['B']=='green')]
Nick ODell
  • 15,465
  • 3
  • 32
  • 66
fred.schwartz
  • 2,023
  • 4
  • 26
  • 53

3 Answers3

12

You should separate the two propositions:

df1=df.loc[~(df['A']=='blue') & ~(df['B']=='green')]
Jim Eisenberg
  • 1,490
  • 1
  • 9
  • 17
7

use eq instead of ==:

df.loc[~(df['A'].eq('blue') & df['B'].eq('green'))]
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • 3
    this prevents you from [operator precedence](https://stackoverflow.com/questions/20333435/pandas-comparison-raises-typeerror-cannot-compare-a-dtyped-float64-array-with) : Note to OP :) – anky Jul 04 '19 at 15:49
  • 1
    Nice comment @anky_91 (-: – piRSquared Jul 04 '19 at 15:54
4

query

Note the != and or as consequence of De Morgan's Law

df.query('A != "blue" or B != "green"')
piRSquared
  • 285,575
  • 57
  • 475
  • 624