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

np.isnan()无法解决「divide by zero encountered in true_divide」警告问题

问题原因分析及解决办法

问题原因

  • np.isnan()无效的核心原因:你遇到的是0值引发的除零警告,但np.isnan()仅用于检测NaN(非数字)值,对0完全不生效,所以这个判断根本没过滤掉0的情况,警告自然会持续出现。
  • 循环逻辑冗余且错误:三层嵌套循环完全没必要,Salary和Games都是长度为10的numpy数组,Pdict.values()就是对应的索引0-9,当前循环会重复遍历所有薪资和场次数据,最终z会被最后一次循环的结果覆盖,得到的plr数组结果也不符合预期。

解决办法

最优方案:修正循环+精准过滤0值

简化循环逻辑,直接通过索引匹配薪资和场次,同时判断场次是否为0,避免除零:

import numpy as np

# 假设前置变量已定义
Pdict = {"KobeBryant":0,"JoeJohnson":1,"LeBronJames":2,"CarmeloAnthony":3,"DwightHoward":4,"ChrisBosh":5,"ChrisPaul":6,"KevinDurant":7,"DerrickRose":8,"DwayneWade":9}
Salary = np.array([KobeBryant_Salary, JoeJohnson_Salary, LeBronJames_Salary, CarmeloAnthony_Salary, DwightHoward_Salary, ChrisBosh_Salary, ChrisPaul_Salary, KevinDurant_Salary, DerrickRose_Salary, DwayneWade_Salary])
Games = np.array([KobeBryant_G, JoeJohnson_G, LeBronJames_G, CarmeloAnthony_G, DwightHoward_G, ChrisBosh_G, ChrisPaul_G, KevinDurant_G, DerrickRose_G, DwayneWade_G])

plr = []
for v in Pdict.values():
    games = Games[v]
    if games == 0:
        # 遇到0值可选择跳过,或赋值为NaN/0等默认值
        plr.append(np.nan)
        continue
    z = np.round(Salary[v] / games, 2)
    plr.append(z)

plr = np.array(plr)
print(plr)

高效向量化处理(无需循环)

利用numpy的向量化操作替代循环,代码更简洁高效:

# 用np.where处理0值:当Games为0时返回NaN,否则计算薪资/场次
plr = np.where(Games == 0, np.nan, np.round(Salary / Games, 2))
print(plr)

临时方案:关闭除零警告(不推荐)

如果只是不想看到警告,但接受除零后的inf结果,可关闭对应警告:

import warnings
warnings.filterwarnings('ignore', category=RuntimeWarning, message='divide by zero encountered in true_divide')

plr = np.round(Salary / Games, 2)
print(plr)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:10:59