Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if row value match one of values in a list, then assign 1/0 in a new column

Tags:

python

pandas

How can I create a new column in a pandas dataframe by following these conditions?

if column 'Ex' match with one of the elements in this list l=['cnn', 'nba', 'agi', 'apple'] then:

Create a new column, S, having value 1 for those elements in the list above.

For example:

Original dataframe:

Ex

cnn
dog
mine
agi

Output expected:

Ex          S

cnn         1
dog         0
mine        0
agi         1

I would approach the problem as follows:

df['S']=df['Ex'].apply(lambda x: any([k in x for k in l]))

to check if a row matches (I do not want a 'contains' condition) one of the value within l. I do not know how to assign values 1 or 0, but I think adding an if statement.


1 Answers

You can just do isin

df['S']=df['Ex'].isin(l).astype(int)
like image 149
BENY Avatar answered Jan 01 '26 18:01

BENY