python - 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:
- -1 如果我的 datetime 列中的值的月份等于 3 并且日期在我称为“shortlongdates”的日期列表中
- 1 如果我的日期时间列中的值的月份等于 10 并且日期在我的称为“shortlongdates”的日期列表中
- 0 否则
现在所有值都在新列中输出为 0 ......为什么?
解决方案
这个问题的原因是链接比较运算符
比较可以任意链接,例如,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。
推荐阅读
- python - 如何使用第二个值对多维进行排序
- javascript - 在前一个块之前有一个带有时间码的块
- bokeh - 如何使用 Bokeh 颜色映射处理 shapefile 中的重叠
- docker - 为什么我的 Docker 项目“开始构建”失败?
- google-calendar-api - 未经授权获取与会者名单
- kotlin - 在 Kotlin 中读取控制台字符输入
- node.js - 获取 http.get Node.js 的前两个字节
- ip - 获取模拟器IP以连接到android模拟器(virtualbox)
- concurrency - 高吞吐量写入 Java 8 并发中的变量?
- c# - 为什么即使条件不正确,我的 while 循环也会执行?