2

I want to create a new Boolean column on a pandas DataFrame based on two conditions. The following errors:

df['new'] = df['old'] != 'A' & df['old'] != 'B'

with

TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]

and and && also error.

What is the correct way to do this?

Dan
  • 45,079
  • 17
  • 88
  • 157
  • 2
    `df['new'] = (df['old'] != 'A') & (df['old'] != 'B')` – cs95 Nov 07 '17 at 17:31
  • 1
    Or `df['new'] = ~df['old'].isin(['A', 'B'])` easier to maintain. – Zero Nov 07 '17 at 17:34
  • Or, `df['new'] = np.logical_and.reduce([df['old'] != v for v in ['A', 'B']])` – Zero Nov 07 '17 at 17:38
  • @cᴏʟᴅsᴘᴇᴇᴅ Thanks, your comment (and Zero's) answer my question but the 'duplicate' you linked to does not as the answer there is applying binary operators to entire `DataFrame`s in an index. The second answer doesn't contain the parenthesis which is what I was missing. – Dan Nov 07 '17 at 17:40
  • The point of the dupe was to show you how to work with multiple conditions... – cs95 Nov 07 '17 at 17:47
  • 1
    You should put each part in parentheses: df['new'] = (df['old'] != 'A') & (df['old'] != 'B'). This will work. – Elnaz Oct 09 '20 at 15:18

0 Answers0