1

I have z = np.array([4.4, 3, 0, np.nan, -1, 6]) and just can't find any quick and friendly solution for easy replacement. I can't believe it's sometimes such not user friendly language.

I tried:

np.where(z == np.nan, -1, z)

nothing happens

np.nan_to_num(z, -1)

changes to zeros

z = [-1 if np.nan(x) else x for x in z]

TypeError: 'float' object is not callable

Why such earsy things can't be just as pure easy? I must use numpy only.

Peter.k
  • 1,475
  • 23
  • 40
  • In your list comprehension, changing `np.nan(x)` to `np.isnan(x)` will work. (Alternatively, and possibly faster, would be: `z[np.isnan(z)] = -1`). – jedwards Jan 20 '19 at 14:19
  • Maybe it's duplicated but I also tried to show Python 4 needs to have better implementations for some base functions. – Peter.k Jan 20 '19 at 14:25

1 Answers1

8

Use np.isnan(x). You can replace like this:

z = np.array([4.4, 3, 0, np.nan, -1, 6])
z[np.isnan(z)] = -1
print(z)

# [ 4.4  3.   0.  -1.  -1.   6. ]
Jeppe
  • 1,830
  • 3
  • 24
  • 33