Skip to main content
 首页 » 编程设计

python之从列表中搜索部分字符串并添加具有该部分字符串的列

2024年10月01日28findumars

我不会在 df.column 中搜索我保存在系列中的部分字符串,也不会用我在每一行中找到的字符串创建一个新列。我的问题的一部分被解决了 pandas: test if string contains one of the substrings in a list :

For example, say I have the series s = pd.Series(['cat','hat','dog','fog','pet']), and I want to find all places where s contains any of ['og', 'at'], I would want to get everything but pet.

解决方法是:

>>> searchfor = ['og', 'at'] 
>>> s[s.str.contains('|'.join(searchfor))] 
0    cat 
1    hat 
2    dog 
3    fog 
dtype: object 

但我想得到

         pet    contains 
    0    cat    at 
    1    hat    at 
    2    dog    og 
    3    fog    og 
    dtype: object 

请您参考如下方法:

使用extract如果没有匹配得到 NaN,那么添加 dropna :

searchfor = ['og', 'at'] 
df['new'] = df['pet'].str.extract('(' + '|'.join(searchfor) + ')', expand=False) 
df = df.dropna(subset=['new']) 
print (df) 
   pet contains1 new 
0  cat        at  at 
1  hat        at  at 
2  dog        og  og 
3  fog        og  og