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

I separate 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'm looking for a way to get 0 instead of Nan without using for loops?

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

+4
source share
2 answers

This below should work and convert all NAN to 0

d[np.isnan(d)] = 0

If you want it all on one line, consider

d = np.nan_to_num(a1/a2)

What converts 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.

+7

, , np.errstate(divide='ignore', invalid='ignore') 0 , , ( ).

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

, , 'ignore' 'warn'.

+4

Source: https://habr.com/ru/post/1619757/


All Articles