【发布时间】: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