Skip to main content
 首页 » 编程设计

python之检查字符串数据帧python中的任何位置是否存在 ''

2025年01月19日24bonelee

背景:我有以下数据框:

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 

目标:

1) 检查每一行以确定'?'存在并返回一个 bool 值(如果 ? 位于 text 列中的任何位置,则返回 True,如果没有,则返回 False ? 存在

2) 用结果创建一个新列

期望的输出t:

    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                result 
0   yeah!               False 
1   tomorrow? let's go  False 
2   today will do       False 

问题:如何更改我的代码以实现我的目标 1)?

请您参考如下方法:

在正则表达式中 ? 是特殊字符,因此需要将其转义或在 contains 中使用 regex=False :

df['result'] = df['text'].astype(str).str.contains('\?') 

或者:

df['result'] = df['text'].astype(str).str.contains('?', regex=False) 

或者:

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