Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a column value in a pandas dataframe is present in a series

Tags:

python

pandas

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)
like image 224
cgclip Avatar asked Dec 11 '25 07:12

cgclip


2 Answers

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
like image 191
Psidom Avatar answered Dec 13 '25 19:12

Psidom


A silly solution is here:

skype_names = set(skype_list.values)
df['skype'] = df.Name.apply(lambda x: x in skype_names).astype(int)
like image 22
DYZ Avatar answered Dec 13 '25 20:12

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!