【问题标题】:Checking if '?' is present anywhere in string data frame python检查是否“?”存在于字符串数据框python中的任何地方
【发布时间】:2018-08-19 03:19:45
【问题描述】:

背景:我有以下数据框:

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) 检查每一行以确定是否为“?”存在并返回一个布尔值(如果?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) 我的目标?

【问题讨论】:

  • 这将起作用df['result'] = df['text'].apply(lambda x: True if '?' in x else False) 您可能需要了解 lambdas 是如何工作的。 Jezrael 的答案通常比使用 lambda 来实现您的目标更好。

标签: python regex pandas lambda


【解决方案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

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2018-07-10
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2018-01-28
    相关资源
    最近更新 更多