3

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
  • 9,210
  • 2
  • 26
  • 54
fred.schwartz
  • 1,879
  • 20
  • 41

3 Answers3

8

You should separate the two propositions:

df1=df.loc[~(df['A']=='blue') & ~(df['B']=='green')]
Jim Eisenberg
  • 1,440
  • 1
  • 8
  • 16
7

use eq instead of ==:

df.loc[~(df['A'].eq('blue') & df['B'].eq('green'))]
Quang Hoang
  • 131,600
  • 10
  • 43
  • 63
  • 2
    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
  • 265,629
  • 48
  • 427
  • 571