if else 不检查 Python 中的两个条件

if else not checking both of the conditions in Python(if else 不检查 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 运算符 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 中的两个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)