Python 更新列';如果行中包含一些单词,则返回s值
对于如何将包含一些单词的行标记为真/假,我有一些疑问 我有一张单子Python 更新列';如果行中包含一些单词,则返回s值,python,pandas,Python,Pandas,对于如何将包含一些单词的行标记为真/假,我有一些疑问 我有一张单子 my_list=['cat','dog','mouse'] 和数据帧中的4列: Col1 Col2 Col3 Col4 ... This is the story of a cat My dad is going to UK False ... My dog's name is Bert The sky is so blue to
my_list=['cat','dog','mouse']
和数据帧中的4列:
Col1 Col2 Col3 Col4
... This is the story of a cat My dad is going to UK False
... My dog's name is Bert The sky is so blue today False
... There is no one that understands me Why are you so sad? False
到目前为止,第一列并不重要。
第4列最初是根据一些初始条件设置的。但是,如果Col2和/或Col3包含我上面提到的列表中的一个单词,我想更改它的值(False/True)
预期的产出将是
Col1 Col2 Col3 Col4
... This is the story of a cat My dad is going to UK True
... The sky is so blue today My dog's name is Bert True
... There is no one that understands me Why are you so sad? False
因为前两行至少包含列表中的一个单词(猫和狗)。
我已尝试使用sr.contains()
:
但它不起作用
我做错了什么?你需要
在这里应用
pattern = '|'.join(my_list)
df[['Col2','Col3']].apply(lambda x : x.str.contains(pattern)).any(1)
或
非常感谢@YOBEN_S。我试着用第二个,但我用了一种错误的方式。
pattern = '|'.join(my_list)
df[['Col2','Col3']].apply(lambda x : x.str.contains(pattern)).any(1)
(df['Col2']+df['Col3']).str.contains(pattern)