Beatriz Alves
Beatriz Alves

Reputation: 83

Adding new column to a DataFrame based on values in a list

Novice programmer here seeking help. I have a Dataframe that looks like this:

       Name  
0  "jackolsen"
1  "IsabelClark"   
2  "JaneDoe"    
3  "JackOlsen"
4  "JACKOLSEN"
5  "MariaSmith"
6  "JohnSmith"
7  "MaryKent"    
8  "MaryKent"   

And a list of names:

l = list("jackolsen", "janedoe", "johnsmith")

My desired output is a new column in the DataFrame which tells me if the name is on the list (value = 1) or not (value = 0)regardless if it is uppercase or lowercase. In this example it would be:

       Name         List
0  "jackolsen"       1
1  "IsabelClark"     0   
2  "JaneDoe"         1
3  "JackOlsen"       1
4  "JACKOLSEN"       1
5  "MariaSmith"      0
6  "JohnSmith"       1
7  "MaryKent"        0
8  "MaryKent"        0

How can I achieve my desired output?

Upvotes: 2

Views: 46

Answers (2)

yatu
yatu

Reputation: 88305

Use str.lower with isin:

df['List'] = df.Name.str.lower().isin(l).view('i1')

print(df)

       Name      List
0    jackolsen     1
1  IsabelClark     0
2      JaneDoe     1
3    JackOlsen     1
4    JACKOLSEN     1
5   MariaSmith     0
6    JohnSmith     1
7     MaryKent     0
8     MaryKent     0

Upvotes: 2

Toby Petty
Toby Petty

Reputation: 4690

df["List"] = df["Name"].str.lower().isin(l).astype(int)

Upvotes: 2

Related Questions