1

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]])
asked Jul 20, 2022 at 6:11

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

One-liner, in-place for x

np.place(x, np.invert(np.isnan(x)), 10.0)
answered Jul 20, 2022 at 6:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.