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

Python按if-else条件参考其他列值新建列时出现Series真值模糊错误

错误原因

pandas的布尔序列进行逻辑运算时,不能使用Python原生的and/or运算符,必须改用位运算符&/|,同时每个独立的判断条件需要用括号包裹,避免运算符优先级冲突。

修正后的代码

import numpy as np
import datetime

# 提前提取当前年月,避免重复计算提升性能
current_year = datetime.datetime.now().year
current_month = datetime.datetime.now().month

conditions = [
    (dfyz['year_x'] < current_year),
    (dfyz['year_x'] == current_year) & (dfyz['mon'] < current_month),
    (dfyz['year_x'] > current_year),
    (dfyz['year_x'] == current_year) & (dfyz['mon'] >= current_month)
]
values = [
    dfyz['yhat'] * dfyz['pct'],
    dfyz['yhat'] * dfyz['pct'],
    dfyz['yhat'] * dfyz['pct_ft'],
    dfyz['yhat'] * dfyz['pct_ft']
]
dfyz['pred_n'] = np.select(conditions, values)

简化优化方案

由于你的判断逻辑最终只有两种输出结果,无需使用np.select,可以用更简洁的np.where实现:

import numpy as np
import datetime

current_year = datetime.datetime.now().year
current_month = datetime.datetime.now().month
is_history = (dfyz['year_x'] < current_year) | ((dfyz['year_x'] == current_year) & (dfyz['mon'] < current_month))
dfyz['pred_n'] = np.where(is_history, dfyz['yhat'] * dfyz['pct'], dfyz['yhat'] * dfyz['pct_ft'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:57:01