Python 熊猫:条件替换为集合

Python 熊猫:条件替换为集合,python,pandas,Python,Pandas,我有一组常见的电子邮件地址,如下所示: common_addresses = set(["yahoo.com", "gmail.com", "hotmail.com"]) 我有一个熊猫数据帧,df,看起来像: id email_domain 1 yahoo.com 2 gmail.com 3 unk.com 4 new.com 我想将不在我的common\u地址中的电子邮件替换为“稀有”。以下是我的尝试: mask = df.email_domain not in common_ad

我有一组常见的电子邮件地址,如下所示:

common_addresses = set(["yahoo.com", "gmail.com", "hotmail.com"])
我有一个熊猫数据帧,
df
,看起来像:

id email_domain
1  yahoo.com
2  gmail.com
3  unk.com
4  new.com
我想将不在我的
common\u地址中的电子邮件替换为“稀有”。以下是我的尝试:

mask = df.email_domain not in common_addresses
df.loc[mask, "email_domain"] = "rare"
我在
mask=…
行上得到一个错误,如下所示:

TypeError: 'Series' objects are mutable, thus they cannot be hashed
我应该如何创建此掩码


谢谢

你就快到了。对于要用于检查成员资格的系列。在您的情况下,您应该将代码更改为:

mask = ~df.email_domain.isin(common_addresses)
df.loc[mask, "email_domain"] = "rare"
此外,您需要使用
~
运算符(而不是
而不是
)对序列进行操作。

另一种方法是使用

df['email_domain'] = df.email_domain.where(df.email_domain.isin(common_addresses), 'rare')

df
输出:

   id email_domain
0   1    yahoo.com
1   2    gmail.com
2   3         rare
3   4         rare