3

I want to replace the NaN in numpy array with a large number such as 99999. I don't want to use numpy.nan_to_num to replace the NaN's with 0 because I want to differentiate between the NaN values and 0 values already in the dataset.

C.Tals
  • 31
  • 1
  • Possible duplicate of [Replace all elements of Python NumPy Array that are greater than some value](http://stackoverflow.com/questions/19666626/replace-all-elements-of-python-numpy-array-that-are-greater-than-some-value) – Eli Sadoff Nov 01 '16 at 20:31
  • You can use that but change the boolean condition to `#isnan()` – Eli Sadoff Nov 01 '16 at 20:32
  • x[np.isnan(x) is True] = 9999 seems only to work for me in one dimension? returning [ [9999, .....,9999], [nan, ...., nan]]. – C.Tals Nov 01 '16 at 20:42
  • I guess this question is different enough. One sec, I'll provide an answer. – Eli Sadoff Nov 01 '16 at 20:44
  • I provided an answer, but I have `x[np.isnan(x)] = 99999` working with a 2-D array. Can you provide an example where it's not working? – Eli Sadoff Nov 01 '16 at 20:49
  • That is working for me as well. Including the 'is True' must have been the problem. Thanks! – C.Tals Nov 01 '16 at 20:54
  • No worries! `is True` is almost always unnecessary. – Eli Sadoff Nov 01 '16 at 20:55

1 Answers1

2

You need to use logical indexing to replace all NaNs with 99999. You can do it like this

x[np.isnan(x)] = 99999

This does work in multiple dimensions.

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61