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 or
and 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 中的两个条件


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01