如果,和,全部包含在应用中(λx:

2024-10-03 09:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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))

enter image description here

我想做的是:

在my dataframe中创建一个新列,该列根据以下条件填充-1、0或1:

  • -1如果“我的日期时间”列中值的月份等于3,并且该日期在我的日期列表中,称为“shortlongdates”
  • 1如果“我的日期时间”列中值的月份等于10,并且该日期在我的日期列表中,称为“shortlongdates”
  • 否则为0

现在所有的值都在新列中以0的形式输出。。。为什么?


Tags: and代码intrue列表datadateif
2条回答

所以我们有一个不可读的东西:

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)

让我们把它写成一个标准函数:

def filterfn(x):
    if x.month == 3 and x.date() in shortlongdates:
        return -1
    elif x.month == 10 and x.date() in shortlongdates:
        return 1
    else:
        return 0

删除一些奇怪的测试(冗余==True)和括号

{}真的是可调用的吗?应该是x.date吗? 如果没有看到你的datalistofdates,就不可能说这可能会失败,但至少我们可以看到它在做什么

这个问题的原因是chaining comparison operators

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

比较,包括成员资格测试和身份测试have same precedence

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

相关问题 更多 >