I have a Pandas DataFrame that looks like this:
>>>df
Application ID Name
0 12 Sally
1 32 Bill
2 35 Dave
3 11 Positivus
4 09 Milan
And a series that looks like this
>>> skype_list
0 Milan
1 Sally
2 Greg
3 Jim
4 Positivus
I want loop through df.Name and create a column that has a 1 if the name is in skype_list and a 0 if it is not. The result should look something like this:
>>>df
Application ID Name skype
0 12 Sally 1
1 32 Bill 0
2 35 Dave 0
3 11 Positivus 1
4 09 Milan 1
Right now I was trying to set up a loop like this:
for x in df.Name:
if x in skype_list:
df['skype'].append(1)
else:
df['skype'].append(0)
Or you can use isin
:
df['skype'] = df.Name.isin(skype_list).astype(int)
df
# Application ID Name skype
#0 0 12 Sally 1
#1 1 32 Bill 0
#2 2 35 Dave 0
#3 3 11 Positivus 1
#4 4 9 Milan 1
A silly solution is here:
skype_names = set(skype_list.values)
df['skype'] = df.Name.apply(lambda x: x in skype_names).astype(int)
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.