首页 > 解决方案 > 需要使用 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

标签: pythonpandas

解决方案


使用Series.str.containswith 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

推荐阅读