if else 不检查 Python 中的两个条件 [英] if else not checking both of the conditions in Python

查看:40
本文介绍了if else 不检查 Python 中的两个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望根据特定条件创建新列 ['pred_n'],条件如下:如果年份小于或等于当前年份 &月份小于当前月份,pred_n 应等于 yhatpct,否则应为 yhatpct_ft.尝试以下语法:

i want new column ['pred_n'] to be created based on certain condition, condition is as follows: if year is less than or equal to current year & month is less than current month, pred_n should be equal to yhatpct else it should be yhatpct_ft. trying following syntax:

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 年开始的月份和年份时,才会显示输出如果我使用

but output shows only if condition though in my data I have month and year from 2019 - 08 onwards and if i use

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']

它只在 else 条件下给出输出

it gives output only for else condition

推荐答案

您目前正在使用 bitwise 运算符 |&,而不是 logical 运算符 orand.大概你真的想要这样的东西:

You are currently using the bitwise operators | and &, rather than the logical operators orand and. Presumably you really want something like:

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

(继续多次调用 now 并不是很好的做法......您的每个调用现在都可能返回一个 不同 值)

(Its not great practice to keep calling now several times ... each of your calls is potentially returning a different value for now)

这篇关于if else 不检查 Python 中的两个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆