我在 Python Pandas 中有 DataFrame,如下所示:
col1
--------
John Simon prd
agc Ann White
BeN and Ann
bad_list = ["Ben", "Wayne"]
我需要做一些类似的事情:创建新列“col2”,如果“col1”中的值来自bad_list,则在“col2”中为该行提供“1”,如果没有,则为“0”。
请注意,应忽略 bad_list 和“col1”中的字母大小,例如“col1”中的值为“BeN”,而 bad_list 中的值为“Ben”,因此“col2”中的值也应为“1”
因此,基于数据框和上述条件,我需要如下结果:
col1 | col2
----------------|------
John Simon prd |0
arc Ann White |0
BeN and Ann |1
“col2”中的最后一行值为“1”,因为“Ben”在 bad_list 中,不管“col1”中的写为 BeN。我怎样才能在 Python Pandas 中做到这一点?
您可以尝试通过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
代码的逐步分解:
由于您的列表 ie bad_list 包含格式中的单词(Ist word 是大写的,其余都是小)所以我们使用这样转换整个 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()
它在检查系列('col1')的行中是否存在 bad_list 中的任何元素后,为我们提供一个布尔系列:
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()
方法将boolean Series 类型转换为 int :
0 0
1 0
2 1
Name: col1, dtype: int32
或者
另一种方法是使用@seanbean 在评论中建议的模块中的IGNORECASE
标志re
:
from re import IGNORECASE
df['col2']=df['col1'].str.contains('|'.join(bad_list), flags=IGNORECASE).astype(int)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句