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

如何解决更新DataFrame的Scores列时出现的ZeroDivisionError

解决DataFrame归一化时的除零错误问题

问题根源

你用np.where仍报错的核心原因是:np.where会先计算所有分支的表达式,再根据条件选择结果。哪怕加了判断条件,df['Scores'] / (df['Correct']+df['Incorrect'])这个除法会被完整计算,分母为0的行还是会触发ZeroDivisionError。

可行解决方案

方案1:使用np.divide的where参数精准控制计算

np.divide支持指定where参数,仅在满足条件的位置执行除法,避免无效计算:

import numpy as np
import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({'Scores': [3, 0], 'Correct': [3, 0], 'Incorrect': [0, 0]})

denominator = df['Correct'] + df['Incorrect']
# 初始化结果为原Scores值,仅对分母>0的行执行除法
df['Scores'] = np.divide(df['Scores'], denominator, out=df['Scores'].copy(), where=denominator > 0)

方案2:过滤目标行后单独计算

先定位分母不为0的行,仅对这些行执行归一化操作,完全避开除零场景:

denominator = df['Correct'] + df['Incorrect']
mask = denominator > 0
# 只更新符合条件的行
df.loc[mask, 'Scores'] = df.loc[mask, 'Scores'] / denominator[mask]

方案3:临时替换分母的0值适配np.where

如果想继续用np.where,可以先把分母中的0替换为不影响结果的临时值(比如1,原Scores为0时0/1结果不变):

denominator = df['Correct'] + df['Incorrect']
denominator_safe = denominator.replace(0, 1)
df['Scores'] = np.where(denominator > 0, df['Scores'] / denominator_safe, df['Scores'])

最终结果

执行任意方案后,DataFrame都会得到预期结果:

ScoresCorrectIncorrect
1.030
000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:06:22