至尊宝的传说
np.log是一个ufunc带where参数的。这告诉它哪些元素x将用于计算。其余的被跳过。这最好与out参数一起使用,如下所示:In [25]: x = np.array([1.,2,0,3,10,0]) In [26]: res = np.zeros_like(x) In [27]: idx = x>0 In [28]: np.log(x) /usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in log #!/usr/bin/python3Out[28]: array([0. , 0.69314718, -inf, 1.09861229, 2.30258509, -inf])In [29]: np.log(x, out=res, where=idx) Out[29]: array([0. , 0.69314718, 0. , 1.09861229, 2.30258509, 0. ])