Antonello
Antonello

Reputation: 6431

How to fill a column conditionally to values in an other column being in a list?

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..

Upvotes: 6

Views: 1823

Answers (2)

Mohamed Ali JAMAOUI
Mohamed Ali JAMAOUI

Reputation: 14689

this should work

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

Upvotes: 7

jezrael
jezrael

Reputation: 862611

I think you can use isin:

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

Upvotes: 3

Related Questions