首页 > 解决方案 > 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']

它仅在其他条件下提供输出

标签: pythonif-statementconditional-statements

解决方案


您当前正在使用按位运算|and &,而不是逻辑运算符orand and。大概你真的想要这样的东西:

now = datetime.now()
if (dfyz['year_x'] < now.year or        
    dfyz['year_x'] == now.year and dfyz['mon'] < now.month
):
    ...

(保持now多次调用不是很好的做法......你的每个调用现在都可能返回不同的值)


推荐阅读