You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas使用带条件判断的Lambda函数新增布尔值列问题求解

错误原因

你写的代码存在3个问题:

  • lambda函数内误用了整列的df.month,应该取当前行的l.month
  • 逻辑运算符|优先级高于==,未加括号会导致运算顺序出错
  • 调用apply未指定axis=1,默认按列遍历无法实现按行判断逻辑

修正后的写法

如果要保留apply的实现方式,修改后代码如下:

df["over_treshold"] = df.apply(lambda l: l.working_time_in_hours >= 40 if (l.month == "June") | (l.month == "July") else l.working_time_in_hours >= 24, axis=1)

更优方案(向量化操作,性能更高)

数据量较大时更推荐用向量化运算代替apply,写法也更简洁:

import numpy as np
df['over_treshold'] = np.where(df['month'].isin(['June', 'July']), 
                              df['working_time_in_hours'] >= 40, 
                              df['working_time_in_hours'] >= 24)

内容的提问来源于stack exchange,提问作者sebikooo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:24:03