首页 > 解决方案 > 如何使用 str.contains() 标记单元格

问题描述

正在清理一个 excel 文档,其中一个列(df_i['Email'])包含电子邮件地址,我需要标记(通过在评论列中添加评论)Gmail 和雅虎电子邮件。我创建了排除列表,但由于某种原因,它只有在我指定要排除的电子邮件索引时才有效。

输入

emails_to_exclude = ('@gmail', '@yahoo')
df_i['Comments'] = np.where(df_i['Email'].str.contains(emails_to_exclude[0] case = False),'to be deleted','')
print(df_i['Comments'])

输出

0                  
1                  
2                  
3                  
4                  
5                  
6                  
7                  
8                  
9                  
10    to be deleted
11                 
12                 
13       

标签: pandas

解决方案


这是因为str.contains不能使用列表,您需要使用正则表达式(正则表达式)将值与OR用管道表示的语句连接起来|

对于您的示例,请下次提供您的数据样本:

df_i = pd.DataFrame({'Email' : ['john@yahoo.com','john@outlook.com','john@gmail.com']})
emails_to_exclude = ('@gmail', '@yahoo')

df_i.loc[df_i['Emails'].str.contains('|'.join(emails_to_exclude)),'comments'] = 'to be deleted'
print(df_i)
                 Emails       comments
0    john@yahoo.com  to be deleted
1  john@outlook.com            NaN
2    john@gmail.com  to be deleted

NaN您可以像这样用空格填充列:

df_i['comments'].fillna('')


推荐阅读