Home > Enterprise >  Replacing all elements except NaN in Python
Replacing all elements except NaN in Python

Time:07-21

I want to replace all elements in array X except nan with 10.0. Is there a one-step way to do it? I present the expected output.

import numpy as np
from  numpy import nan

X = np.array([[3.25774286e 02, 3.22008654e 02, nan, 1.85356823e 02,
        1.85356823e 02, 3.22008654e 02, nan, 3.22008654e 02]])

The expected output is

X = array([[10.0, 10.0, nan, 10.0,
        10.0, 10.0, nan, 10.0]])

CodePudding user response:

You can get an array of True/False for nan location using np.isnan, invert it, and use it to replace all other values with 10.0

indices = np.isnan(X)
X[~indices] = 10.0
print(X) # [[10. 10. nan 10. 10. 10. nan 10.]]

CodePudding user response:

You can use a combination of numpy.isnan and numpy.where.

>>> np.where(np.isnan(X), X, 10)
array([[10., 10., nan, 10., 10., 10., nan, 10.]])

CodePudding user response:

One-liner, in-place for x

np.place(x, np.invert(np.isnan(x)), 10.0)
  • Related