Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 869
Yashu Seth Avatar asked Dec 13 '15 23:12

Yashu Seth


2 Answers

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.

like image 105
Geotob Avatar answered Sep 28 '22 13:09

Geotob


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

like image 42
ilyas patanam Avatar answered Sep 28 '22 13:09

ilyas patanam