python - 如何测试字符串是否包含存储在熊猫列表列中的子字符串之一?
问题描述
我的问题与如何在熊猫中测试字符串是否包含列表中的子字符串之一非常相似?除了要检查的子字符串列表因观察而异并存储在列表列中。有没有办法通过引用系列以矢量化方式访问该列表?
示例数据集
import pandas as pd
df = pd.DataFrame([{'a': 'Bob Smith is great.', 'b': ['Smith', 'foo'])},
{'a': 'The Sun is a mass of incandescent gas.', 'b': ['Jones', 'bar']}])
print(df)
我想生成第三列“c”,如果任何“b”字符串是其各自行的“a”的子字符串,则它等于 1,否则为零。也就是说,我希望在这种情况下:
a b c
0 Bob Smith is great. [Smith, foo] 1
1 The Sun is a mass of incandescent gas. [Jones, bar] 0
我的尝试:
df['c'] = df.a.str.contains('|'.join(df.b)) # Does not work.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_4092606/761645043.py in <module>
----> 1 df['c'] = df.a.str.contains('|'.join(df.b)) # Does not work.
TypeError: sequence item 0: expected str instance, list found
解决方案
您可以只使用zip
并列出理解:
df['c'] = [int(any(w in a for w in b)) for a, b in zip(df.a, df.b)]
df
# a b c
#0 Bob Smith is great. [Smith, foo] 1
#1 The Sun is a mass of incandescent gas. [Jones, bar] 0
如果您不关心大小写:
df['c'] = [any(w.lower() in a for w in b) for a, b in zip(df.a.str.lower(), df.b)]
推荐阅读
- azure-active-directory - 在 Azure OIDC 注销后,应该将什么内容安全策略标头值重定向回应用程序
- java - 如何在没有 PG 服务器和 Web 控制台的情况下启动 H2 数据库命令行?
- php - 基于帖子术语的 Wordpress 搜索
- django - 如何在 docker 中设置 celery beat?
- python - Python中if语句的问题
- linked-list - 我可以只使用 ALLOCATABLE 变量而不是指针在 Fortran 中创建链接列表吗?
- python - Python 在一行中查找单词并将其附加到一个新的文本文件中
- r - 从向量制作对称矩阵
- django - 如何使用 Django-quill-editor 从数据库中以 Quill 格式提取数据并提供给 Quill 表单
- python - Discord Python Bot 播放音乐 - url 是缺少的必需参数