Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python syntax if in list function

I am trying to find the proper python syntax to create a flag with a value of yes if columnx contains any of the following numbers: 1, 2, 3, 4, 5.

def create_flag(df):
    if df['columnx'] in (1,2,3,4,5):
        return df['flag']=='yes'

I get the following error.

TypeError: invalid type comparison

Is there an obvious mistake in my syntax?

like image 554
pynewbee Avatar asked Sep 24 '26 17:09

pynewbee


1 Answers

Use np.where with pandas isin as:

df['flag'] = np.where(df['columnx'].isin([1,2,3,4,5]),'yes','no')
like image 105
Space Impact Avatar answered Sep 27 '26 07:09

Space Impact