After division by 0, replace NaN with 0 in numpy arrays

谁说胖子不能爱 提交于 2019-12-23 09:53:41

问题


I am dividing two numpy arrays:

>>> import numpy as np
>>> a1 = np.array([[ 0,  3],
                   [ 0,  2]])
>>> a2 = np.array([[ 0,  3],
                   [ 0,  1]])
>>> d = a1/a2
>>> d
array([[ nan,   1.],
       [ nan,   2.]])
>>> where_are_NaNs = np.isnan(d)
>>> d[where_are_NaNs] = 0
>>> d
>>> array([[ 0.,  1.],
           [ 0.,  2.]])

I am looking for a way to get 0 instead of Nan without using for loops?

Does numpy have a similar function to fillna() in pandas?


回答1:


This below should work and convert all NANs to 0

d[np.isnan(d)] = 0

If you want it all on one line, consider

d = np.nan_to_num(a1/a2)

Which will convert all NANs to 0, see here: http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.nan_to_num.html

Note: When dividing by 0, you should follow @imp9's solution below to avoid unnecessary warnings or errors.




回答2:


You should probably do the division in the context of np.errstate(divide='ignore', invalid='ignore') so that division by 0 doesn't raise an error or warnings, whether the dividend itself is zero or not (the two are separate warnings).

with np.errstate(divide='ignore', invalid='ignore'):
    d = a1/a2
#Geotob's solution
d[np.isnan(d)] = 0

If you want it to raise warnings the change 'ignore' to 'warn'. Reference



来源:https://stackoverflow.com/questions/34257436/after-division-by-0-replace-nan-with-0-in-numpy-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!