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

捕获ZeroDivisionError后DataFrame列百分比计算结果全为空值排查

问题原因分析

你的代码核心逻辑错误在于try-except块的作用范围完全不符合需求:
Pandas是向量化运算,当你执行整列的除法计算时,只要列中有任意一行出现metric_thismonth=0,就会触发ZeroDivisionError,此时except块会直接将整个metric_pctdiff列赋值为np.nan,而非仅标记出错的行。这就是为什么差值列有非空值,但百分比列全为null的根本原因。

正确解决方法

不需要用try-except捕获异常,直接通过向量化条件判断,仅对分母非零的行计算百分比,其余行设为nan。推荐两种简洁写法:

方法1:使用np.where(直观易懂)

import numpy as np

df_ex['metric_diff'] = df_ex['metric_lastmonth'] - df_ex['metric_thismonth']
# 先判断分母是否为0,是则设为nan,否则计算百分比差值
df_ex['metric_pctdiff'] = np.where(
    df_ex['metric_thismonth'] == 0,
    np.nan,
    df_ex['metric_diff'] / df_ex['metric_thismonth']
)

方法2:使用Pandas的mask方法(更简洁)

df_ex['metric_diff'] = df_ex['metric_lastmonth'] - df_ex['metric_thismonth']
# 先计算所有行的百分比,再将分母为0的行替换为nan
df_ex['metric_pctdiff'] = (df_ex['metric_diff'] / df_ex['metric_thismonth']).mask(df_ex['metric_thismonth'] == 0)

补充:处理NaN值的情况

如果你的数据中存在NaN值,可以在条件中加入非空判断,避免无效运算:

df_ex['metric_pctdiff'] = np.where(
    (df_ex['metric_thismonth'] == 0) | df_ex['metric_thismonth'].isna(),
    np.nan,
    df_ex['metric_diff'] / df_ex['metric_thismonth']
)

内容的提问来源于stack exchange,提问作者Pythonlearner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:52:47