6

In pandas dataframe, how to fill the value of a column conditionally to values in an other column being part of a list ?

This is very similar to this SO question, but when I apply:

df['type'] = np.where(df['food'] in ['apple', 'banana', 'kiwi'], 'fruit', 'oth. food')

I got an error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I suppose the in operator has been not overridden to work with vectors..

Community
  • 1
  • 1
Antonello
  • 6,092
  • 3
  • 31
  • 56
  • Are you after `df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')` – EdChum Apr 11 '16 at 14:12

2 Answers2

7

this should work

df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117
3

I think you can use isin:

df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252