python - 找到列中的值与列表 Python 中的值不匹配的行

标签 python pandas dataframe for-loop list-comprehension

我有一个带有 ID 和一些电子邮件地址的数据框

personid  sup1_email      sup2_email         sup3_email        sup4_email
1         evan.o@abc.com  jon.k@abc.com      kelm.q@abc.com    john.d@abc.com 
5         evan.o@abc.com  polly.u@abc.com    jim.e@ABC.COM     nan
11        jim.y@abc.com   manfred.a@abc.com  greg.s@Abc.com    adele.a@abc.com 
52        jim.y@abc.com   manfred.a@abc.com  greg.s@Abc.com    adele.a@abc.com
65        evan.o@abc.com  lenny.t@yahoo.com  john.s@abc.com    sally.j@ABC.com
89        dom.q@ABC.com   laurie.g@Abc.com   topher.u@abc.com  ross.k@qqpower.com

我想找到与接受的电子邮件值列表不匹配的行(即不是“@abc.com”、“@ABC.COM”、“@Abc.com”)。我想要得到的是这个

personid  sup1_email      sup2_email         sup3_email        sup4_email
65        evan.o@abc.com  lenny.t@yahoo.com  john.s@abc.com    sally.j@ABC.com
89        dom.q@ABC.com   laurie.g@Abc.com   topher.u@abc.com  ross.k@qqpower.com

我编写了以下代码并且它可以工作,但我必须手动检查每个 sup_email 列并重复该过程,这是低效的

#list down all the variations of accepted email domains
email_adds = ['@abc.com','@ABC.COM','@Abc.com']
#combine the variations of email addresses in the list
accepted_emails = '|'.join(email_adds)


not_accepted = df.loc[~df['sup1_email'].str.contains(accepted_emails, na=False)]

我想知道是否有更有效的方法使用 for 循环来执行此操作。到目前为止我所管理的是显示一个包含未接受电子邮件的列,但它没有显示包含未接受电子邮件的行。感谢我能得到的任何形式的帮助,谢谢。

sup_emails = df[['sup1_email','sup2_email', 'sup3_email', 'sup4_email']]

#for each sup column, check if the accepted email addresses are not in it
for col in sup_emails:
    if any(x not in col for x in accepted_emails):
        print(col)

最佳答案

你可以这样做:

# list down all the variations of accepted email domains
email_adds = ['@abc.com','@ABC.COM','@Abc.com']

# combine the variations of email addresses in the list
accepted_emails = '|'.join(email_adds)

# create a single email column
melted = df.melt('personid')

# check the matching emails
mask = melted['value'].str.contains(accepted_emails, na=True)

# filter out the ones that do not match
mask = df['personid'].isin(melted.loc[~mask, 'personid'])

print(df[mask])

输出

   personid      sup1_email  ...        sup3_email          sup4_email
4        65  evan.o@abc.com  ...    john.s@abc.com     sally.j@ABC.com
5        89   dom.q@ABC.com  ...  topher.u@abc.com  ross.k@qqpower.com

[2 rows x 5 columns]

关于python - 找到列中的值与列表 Python 中的值不匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65352948/

相关文章:

python / Pandas : how to read a csv in cp1252 with a first row to delete?

python - Pandas groupby 保持顺序

python - 如何在 Pandas 中保存符合特定条件的先前结果

r - 在R中,如何将data.frame的聚合转换为data.table的聚合?

python - 如何在 pytest 中处理 sys.argv?

python - 为什么 numpy.empty_like() 返回用零填充的数组不安全?

python - 暂停和恢复工作在 scrapy 项目中不起作用

python - Pykka:如何在 Actor 停止时取消其待处理消息队列

python - 从 Pandas 数据框中的其他列分配列的值

r - 在 R 中,按列名而不是列号对列进行分组