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

Yashu Seth picture Yashu Seth · Dec 14, 2015 · Viewed 14.2k times · Source

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?

Answer

Geotob picture Geotob · Dec 14, 2015

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.