numpy的:由零与分返回0 [英] NumPy: Return 0 with divide by zero

查看:597
本文介绍了numpy的:由零与分返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图执行一个Python元素明智的鸿沟,但如果遇到一个零,我需要的商数只是零。

I'm trying to perform an element wise divide in python, but if a zero is encountered, I need the quotient to just be zero.

例如:

array1 = np.array([0, 1, 2])
array2 = np.array([0, 1, 1])

array1 / array2 # should be np.array([0, 1, 2])

我总是可以只使用一个for循环,通过我的数据,但要真正利用numpy的的优化,我需要的分频功能由零错误划分后返回0,而不是忽略错误的。

I could always just use a for-loop through my data, but to really utilize numpy's optimizations, I need the divide function to return 0 upon divide by zero errors instead of ignoring the error.

除非我失去了一些东西,它似乎并不<一个href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html#numpy.seterr\">numpy.seterr()可以根据错误的返回值。有没有人对我怎么能获得最好的numpy的设置,同时我自己的被零除错误处理任何其他建议?

Unless I'm missing something, it doesn't seem numpy.seterr() can return values upon errors. Does anyone have any other suggestions on how I could get the best out of numpy while setting my own divide by zero error handling?

推荐答案

大厦@Franck Dernoncourt的回答,固定-1 / 0:

Building on @Franck Dernoncourt's answer, fixing -1 / 0:

def div0( a, b ):
    """ ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] """
    with np.errstate(divide='ignore', invalid='ignore'):
        c = np.true_divide( a, b )
        c[ ~ np.isfinite( c )] = 0  # -inf inf NaN
    return c

div0( [-1, 0, 1], 0 )
array([0, 0, 0])

这篇关于numpy的:由零与分返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆