如何将二维numpy数组中除零得到的inf值替换为0
问题场景说明
当前为numpy向量化除法中除数为0返回inf的替换需求,以下分别提供try-except实现方案,以及效率更高的numpy原生实现方案:
方案1:通过try-except语句实现
由于numpy默认除零操作仅返回inf并抛出警告、不会触发异常,需要先修改numpy的错误处理规则,让除零操作抛出可捕获的异常,逐元素计算实现:
import numpy as np x1 = np.array([[1,4,2,1], [1,1,4,5], [0.5,0.3, 1,6], [0.8,0.2,0.7,1]]) x2 = np.array([[7,0,2,3], [8,0,4,5], [0.1,0, 2,6], [0.1,0,0.16666667,6]]) # 设置除零操作抛出异常 np.seterr(divide='raise') res = np.zeros_like(x1, dtype=np.float64) # 逐元素遍历计算 for i in range(x1.shape[0]): for j in range(x1.shape[1]): try: res[i][j] = np.true_divide(x1[i][j], x2[i][j]) except FloatingPointError: res[i][j] = 0 # 恢复numpy默认错误处理规则 np.seterr(divide='warn') print(res)
该方案需要嵌套循环逐元素处理,数组规模较大时执行效率极低,仅适合极小体量的数组场景
方案2:更优的numpy原生向量化实现(推荐)
完全不用循环,利用numpy的向量化操作即可快速完成inf替换,运行效率是逐元素循环的数百到数千倍,常用实现方式有以下三种:
方式A:计算后替换inf
import numpy as np x1 = [[1,4,2,1], [1,1,4,5], [0.5,0.3, 1,6], [0.8,0.2,0.7,1]] x2 = [[7,0,2,3], [8,0,4,5], [0.1,0, 2,6], [0.1,0,0.16666667,6]] res = np.true_divide(x1, x2) # 直接把所有inf值替换为0 res[np.isinf(res)] = 0
方式B:计算时直接跳过除零位置(无警告)
可以在除法运算时就指定仅在除数不为0的位置执行计算,其余位置默认填充0,不会触发除零警告:
res = np.divide(x1, x2, where=np.array(x2)!=0, out=np.zeros_like(x1, dtype=np.float64))
方式C:统一处理异常值
如果同时需要处理inf、NaN等多种异常值,可以直接使用np.nan_to_num方法:
res = np.true_divide(x1, x2) res = np.nan_to_num(res, posinf=0, neginf=0, nan=0)
内容的提问来源于stack exchange,提问作者manacoder
相关产品推荐
相关产品推荐

