You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:34:57