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]])
3 Answers 3
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.]]
answered Jul 20, 2022 at 6:16
Guy
51.2k10 gold badges49 silver badges96 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.]])
answered Jul 20, 2022 at 6:18
Mahdi F.
24.1k5 gold badges25 silver badges32 bronze badges
Comments
One-liner, in-place for x
np.place(x, np.invert(np.isnan(x)), 10.0)
answered Jul 20, 2022 at 6:33
Stepan Zakharov
7556 silver badges14 bronze badges
Comments
lang-py