首页 > 解决方案 > if 和 elif 都包含在 apply(lambda x:

问题描述

我有以下代码:

data['ShortLongFlag'] = data['End DateTime'].apply(lambda x:
                                                   -1 if (x.month == 3 and x.date() in shortlongdates == True) else (1 if (x.month == 10 and x.date() in shortlongdates == True) else 0))

在此处输入图像描述

我想要做的是以下几点:

在我的数据框中创建一个新列,根据以下条件填充 -1、0 或 1:

现在所有值都在新列中输出为 0 ......为什么?

标签: pythonpandasdatedatetimelambda

解决方案


这个问题的原因是链接比较运算符

比较可以任意链接,例如,x < y <= z 等价于 x < y 和 y <= z,除了 y 只计算一次(但在这两种情况下,当找到 x < y 时根本不计算 z是假的)。

比较,包括成员资格测试和身份测试具有相同的优先级

IE

x.month == 3 and x.date() in shortlongdates == True

x.month == 3 and x.date() in shortlongdates and shortlongdates == True

请注意,它可以写成x.month == 3 and x.date() in shortlongdates,或使用括号。然而,正如评论中已经说明的那样,这个 lambda 最好写成常规函数。

def replace_value(x):
    if x.date() in shortlongdates:
        return {3:-1, 10:1}.get(x.month, 0)
    return 0

如果您坚持,我会留给您将其转换回[更简单的] lambda。


推荐阅读