Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the values of an array from nan to zero

I have an array A on python that has some nan values created by numpy.nan. I want to set all the nan values to zero using A[A==numpy.nan] = 0. It doesn't change the array at all. Why is that?

like image 396
f.ashouri Avatar asked Dec 15 '22 17:12

f.ashouri


2 Answers

You want np.isnan:

A[np.isnan(A)] = 0

The problem with your code is that (according to IEEE), nan doesn't equal anything -- even itself.

As a side note, there's also

  • np.isinf -> (+/- infinity)
  • np.isfinite -> (not infinity or NaN)
  • np.isposinf -> (+ infinity)
  • np.isneginf -> (- infinity)
like image 178
mgilson Avatar answered Dec 18 '22 07:12

mgilson


You can use the numpy function to change all the nan value at matrix x to zero.

numpy.nan_to_num(x)
like image 42
ybdesire Avatar answered Dec 18 '22 06:12

ybdesire