[英]Check if a column value in a pandas dataframe is present in a series
I have a Pandas DataFrame that looks like this: 我有一个看起来像这样的Pandas DataFrame:
>>>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. 我想循环通过df.Name并创建一个列,如果名称在skype_list中,则为1,如果不在,则为0。 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
: 或者你可以使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.