简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM