您可以尝试通过str.title()
,str.contains()
and astype()
method:
df['col2']=df['col1'].str.title().str.contains('|'.join(bad_list)).astype(int)
的输出df
:
col1 col2
0 John Simon prd 0
1 agc Ann White 0
2 BeN and Ann 1
代码的逐步细分:
由于您的列表(即 bad_list)包含格式中的单词(Ist 单词为大写,其余均为小写),因此我们使用以下方法转换整个 Series('col1')Series.str.title()
所以现在 Series('col1') 看起来像:
0 John Simon Prd
1 Agc Ann White
2 Ben And Ann
Name: col1, dtype: object
然后我们使用str.contains()
检查 bad_list 中的任何元素是否存在于 Series('col1') 行中后,为我们提供了一个布尔系列:
0 False
1 False
2 True
Name: col1, dtype: bool
Note:
这是里面的代码contains()
method:
'|'.join(bad_list)
#giving you a string(output of above code):
'Ben|Wayne'
最后我们将 boolean Series 类型转换为 int viaastype()
method:
0 0
1 0
2 1
Name: col1, dtype: int32
OR
另一种方法是使用IGNORECASE
标志来自re
@seanbean 在评论中建议的模块:
from re import IGNORECASE
df['col2']=df['col1'].str.contains('|'.join(bad_list), flags=IGNORECASE).astype(int)