How to fill a column conditionally with values ​​in another column in the list?

In a pandas dataframe, how do I populate a column value conditionally with values ​​in another column that is 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')

There was an error:

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

I believe that the operator has innot been redefined to work with vectors.

+4
source share
2 answers

it should work

df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')
+4
source

I think you can use isin:

df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')
+2
source

All Articles