Python中IF-OR条件无法处理Float(nan),如何合并多条件?
问题修复与优化
原代码的核心问题
- 语法错误:第一个判断条件里
row["Withdrawal*"] != '']多写了一个右方括号,正确写法是row["Withdrawal*"] != '' - NaN判断失效:
float('nan') == float('nan')结果为False,直接用!= ''或直接比较NaN无法识别空值,必须用专门的NaN检测方法 - 逻辑遗漏:你要求满足条件3、4时执行
amount.text = str(row["Deposit*"] * -1),但原代码漏写了* -1的操作 - 类型风险:如果
row中的金额是字符串格式,直接相乘会报错,需要先转成数值类型
修正后的双条件代码
假设你用的是Pandas(处理带NaN的行数据最常用的库),代码调整如下:
import pandas as pd vch_type = str(row["Vch Type*"]) # 处理条件1、2:Payment 或 含有效Withdrawal的Contra if vch_type == "Payment" or (vch_type == "Contra" and pd.notna(row["Withdrawal*"])): amount.text = str(float(row["Withdrawal*"]) * -1) # 处理条件3、4:Receipt 或 含有效Deposit的Contra elif vch_type == "Receipt" or (vch_type == "Contra" and pd.notna(row["Deposit*"])): amount.text = str(float(row["Deposit*"]) * -1) else: x = 0
如果不是Pandas环境,用通用方法检测NaN:
import math def is_valid_amount(val): # 兼容数值型NaN和空字符串 try: return not math.isnan(float(val)) except (TypeError, ValueError): return val != '' vch_type = str(row["Vch Type*"]) if vch_type == "Payment" or (vch_type == "Contra" and is_valid_amount(row["Withdrawal*"])): amount.text = str(float(row["Withdrawal*"]) * -1) elif vch_type == "Receipt" or (vch_type == "Contra" and is_valid_amount(row["Deposit*"])): amount.text = str(float(row["Deposit*"]) * -1) else: x = 0
合并为单个IF语句的写法
可以整合逻辑,但可读性不如双条件版本,仅做参考:
import pandas as pd vch_type = str(row["Vch Type*"]) is_withdrawal_case = vch_type == "Payment" or (vch_type == "Contra" and pd.notna(row["Withdrawal*"])) is_deposit_case = vch_type == "Receipt" or (vch_type == "Contra" and pd.notna(row["Deposit*"])) if is_withdrawal_case or is_deposit_case: amount.text = str(float(row["Withdrawal*"] if is_withdrawal_case else row["Deposit*"]) * -1) else: x = 0
内容的提问来源于stack exchange,提问作者Viv
相关产品推荐
相关产品推荐

