pandas - 如何使用 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
解决方案
这是因为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('')
推荐阅读
- datatable - 闪亮的 DT::renderdatatable
- excel - 将 Tally ERP 9 实时数据与 Excel 工作簿连接起来
- java - 在 JDBC 上使用键盘插入数据时出错
- javascript - 当扩展一个类并使用原始类的属性时,你在 super() 里面放了什么
- wordpress - Wordpress 网站未在 IE 中加载(Firefox 和 Chrome 都可以)
- dia - 如何更改 Dia 中的字体并修复其字体渲染问题?
- macos - 通过命令行将文件 URL 和参数发送到(正在运行的)macOS 应用程序
- javascript - Unhandle Promise sequelize hooks 和加密密码
- ansible - 使用 ansible 在循环中将主机变量写入文件
- python - 如何创建和访问模板函数的动态变量名称?