python - if else 不检查 Python 中的两个条件
问题描述
我希望根据特定条件创建新列 ['pred_n'],条件如下:如果年份小于或等于当前年份且月份小于当前月份,则 pred_n 应等于 yhatpct 否则应为yhatpct_ft。尝试以下语法:
if((dfyz['year_x'] < datetime.now().year) | ((dfyz['year_x'] == datetime.now().year) & (dfyz['mon'] < datetime.now().month))):
dfyz['pred_n'] = dfyz['yhat']*dfyz['pct']
else:
dfyz['pred_n'] = dfyz['yhat']*dfyz['pct_ft']
但输出仅显示条件虽然在我的数据中我有从 2019 年到 08 年的月份和年份,并且如果我使用
if ((dfyz['year_x'] < datetime.now().year) | ((dfyz['year_x'] == datetime.now().year) & (dfyz['mon'] < datetime.now().month))):
dfyz['pred_n'] = dfyz['yhat']*dfyz['pct']
elif (((dfyz['year_x'] == datetime.now().year) & (dfyz['mon'] >= datetime.now().month)) | ((dfyz['year_x'] > datetime.now().year))):
dfyz['pred_n'] = dfyz['yhat']*dfyz['pct_ft']
它仅在其他条件下提供输出
解决方案
您当前正在使用按位运算符|
and &
,而不是逻辑运算符or
and and
。大概你真的想要这样的东西:
now = datetime.now()
if (dfyz['year_x'] < now.year or
dfyz['year_x'] == now.year and dfyz['mon'] < now.month
):
...
(保持now
多次调用不是很好的做法......你的每个调用现在都可能返回不同的值)
推荐阅读
- php - .htaccess 重定向到子域并隐藏在 uri 中?
- arrays - 查看没有索引的数组时无法读取未定义的属性“映射”
- excel - 在 VBA 中为生成的数字创建记录
- java - 刷新时收到致命警报:handshake_failure
- r - 将街道地址变成组件
- c - C 宏 _Generic 给出了意外的编译器错误
- python - 规范化,同时将 'dst' 的值保持为空数组
- c# - '强类型' 泛型集合,包含任何
给定接口/类的 - python - requests.exceptions.ConnectionError:无法建立新连接:[Errno 111] 连接被拒绝
- css - 角度内容不会滚动