检查是否'';在字符串数据帧python中的任何位置都存在
背景:我有以下数据帧:检查是否'';在字符串数据帧python中的任何位置都存在,python,regex,pandas,lambda,Python,Regex,Pandas,Lambda,背景:我有以下数据帧: import pandas as pd d = {'text': ["yeah!", "tomorrow? let's go", "today will do"]} df = pd.DataFrame(data=d) df['text'].apply(str) 输出: text 0 yeah! 1 tomorrow? let's go 2 today will do text result 0 yeah!
import pandas as pd
d = {'text': ["yeah!", "tomorrow? let's go", "today will do"]}
df = pd.DataFrame(data=d)
df['text'].apply(str)
输出:
text
0 yeah!
1 tomorrow? let's go
2 today will do
text result
0 yeah! False
1 tomorrow? let's go False
2 today will do False
目标:
1) 检查每一行以确定是否存在“?”,并返回一个布尔值(如果?
在文本列中的任何位置,则返回True
,如果不存在?
则返回False
)
2) 创建一个包含结果的新列
所需输出ut:
text result
0 yeah! False
1 tomorrow? let's go True
2 today will do False
问题:
我正在使用下面的代码
df['Result'] = df.text.apply(lambda t: t[-1]) is "?"
实际产出:
text
0 yeah!
1 tomorrow? let's go
2 today will do
text result
0 yeah! False
1 tomorrow? let's go False
2 today will do False
问题:如何更改代码以实现我的目标?在regex中?
是特殊字符,因此需要将其转义或在中使用regex=False
:
或:
或:
这将起作用df['result']=df['text']。应用(lambda x:True如果x中的“?”否则为False)
您可能需要了解lambda是如何工作的。Jezrael的答案通常比使用lambda来实现您的目标要好。
df['result'] = df['text'].apply(lambda x: '?' in x )
print (df)
text result
0 yeah! False
1 tomorrow? let's go True
2 today will do False