0 votes
1 view
in Data Science by (7.5k points)
edited ago by

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

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

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

For example:

The Original data frame:

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 values within l. I do not know how to assign the values 1 or 0, but I think, I need to add an if statement.

1 Answer

0 votes
by (15.3k points)
edited ago by

You can just do isin

df['S']=df['Ex'].isin(l).astype(int)

Improve your knowledge in data science from scratch using Data science online courses 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...