Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited 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 (36.8k points)
edited 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!

29.3k questions

30.6k answers

501 comments

104k users

Browse Categories

...