你可以试试via
str.title()
,
str.contains()
和
astype()
方法:
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_列表)包含格式中的单词(Ist word为大写,其余都很小),所以我们使用
Series.str.title()
所以现在这个系列(‘col1’)看起来像:
0 John Simon Prd
1 Agc Ann White
2 Ben And Ann
Name: col1, dtype: object
然后我们使用
str.contains()
在检查bad_列表中的任何元素是否存在于序列行('col1')中后,我们得到了一个布尔序列:
0 False
1 False
2 True
Name: col1, dtype: bool
注:
这是里面的代码
contains()
方法:
'|'.join(bad_list)
#giving you a string(output of above code):
'Ben|Wayne'
最后,我们将布尔级数通过
astype()
方法:
0 0
1 0
2 1
Name: col1, dtype: int32
或
另一种方法是使用
IGNORECASE
来自
re
@seanbean在评论中建议的模块:
from re import IGNORECASE
df['col2']=df['col1'].str.contains('|'.join(bad_list), flags=IGNORECASE).astype(int)