Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 509
Antonello Avatar asked Apr 11 '16 14:04

Antonello


People also ask

How do I get the value of a column based on another column value?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression.

How do you fill missing values based on another column?

Using fillna() to fill values from another column Here, we apply the fillna() function on “Col1” of the dataframe df and pass the series df['Col2'] as an argument. The above code fills the missing values in “Col1” with the corresponding values (based on the index) from “Col2”.


2 Answers

this should work

df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')
like image 198
Mohamed Ali JAMAOUI Avatar answered Oct 09 '22 22:10

Mohamed Ali JAMAOUI


I think you can use isin:

df['type'] = np.where(df['food'].isin(['apple', 'banana', 'kiwi']), 'fruit', 'oth. food')
like image 20
jezrael Avatar answered Oct 09 '22 22:10

jezrael