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


基础教程推荐
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01