if else not checking both of the conditions in Python(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 运算符 or 和 and.大概你真的想要这样的东西:
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 中的两个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:if else 不检查 Python 中的两个条件
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
