python - 需要使用 pandas.str() 使用字符串列表从列中选择值
问题描述
需要从字符串列表中搜索字符串列值。搜索列表中的字符串只是列中值的子字符串
df = pd.DataFrame(data={'text':['abc def', 'def ghi', 'poi opo', 'aswwf', 'abcs sd'], 'id':[1, 2, 3, 4, 5]})
Out [1]:
text id
0 abc def 1
1 def ghi 2
2 poi opo 3
3 aswwf 4
4 abcs sd 5
search = ['abc', 'poi']
必需的:
Out [2]:
text id
0 abc def 1
1 poi opo 3
2 abcs sd 5
解决方案
使用Series.str.contains
with boolean indexing
- list 的所有值都由|
regex连接OR
:
pat = '|'.join(search)
df1 = df[df['text'].str.contains(pat)]
print (df1)
text id
0 abc def 1
2 poi opo 3
4 abcs sd 5
推荐阅读
- nativescript-angular - 使用 Nativescript RadDataForm:“typeof com”类型上不存在属性“telerik”
- c# - An item with the same key has already been added - Visual Studio Stops Responding
- java - 尝试在空对象引用 RecyclerView 适配器错误上调用虚拟方法“int java.util.ArrayList.size()”
- java - 合并排序无法正常工作。数组中的数字未排序
- javascript - 在 mouseover/mouseout 上更新布尔值
- python - 将预训练的词嵌入添加到编码器解码器中
- android - 如何添加网址
在network-security-config.xml文件Android中动态 - laravel - 我是否需要使用多个 GoogleMyBusiness API 密钥?
- java - 如何从 Java 应用程序中运行 clojure uberjar?
- flutter - Cubit 和 Bloc 有什么区别?