numpy 分母为零的处理办法
如果使用for循环逐项处理数据,就丧失了numpy数组运算的优势。有以下2法可以避免for循环。
法一
利用numpy.divide
,不为0的项正常除,为0的项赋一个默认值。
numpy.divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'true_divide'>
2个关键参数:初始化一个结果数组out
,在where
数组为真的地方,就会执行除法,结果存到out
的对应位置,在where
数组为假的地方,不操作,保持out
原来的值。
-
out ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
-
where array_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
示例:
>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)
# If you don't pass `out` the indices where (b == 0) will be uninitialized!
>>> c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
>>> print(c)
[ 0. 0. 0. 1. 1.5]
法二
感谢@~华仔呀的方法:numpy中np.finfo用法
"""
np.finfo使用方法
eps是一个很小的非负数
除法的分母不能为0的,不然会直接跳出显示错误。
使用eps将可能出现的零用eps来替换,这样不会报错。
"""
import numpy as np
x = np.array([1, 2, 3], dtype=float)
eps = np.finfo(x.dtype).eps # eps = 2.220446049250313e-16 type = <class 'numpy.float64'>
print(eps, type(eps))
height = np.array([0, 2, 3], dtype=float)
height = np.maximum(height, eps) #一旦height中出现0,就用eps进行替换
print(height) #[2.22044605e-16 2.00000000e+00 3.00000000e+00]
dy = x / height
print(dy) #[4.50359963e+15 1.00000000e+00 1.00000000e+00]