0

I have a 2D numpy array and want to replace each NaN in each row by the corresponding value from a 1D array. For example, this matrix:

[[1.  2. NaN]
 [4.  5.  6.]
 [NaN NaN 9.]]

using vector [3. 7. 8.] would be converted to:

[[1. 2. 8.]
 [4. 5. 6.]
 [3. 7. 9.]]

How to do it without iterating over indices?

1 Answer 1

1

Use numpy.where and broadcasting:

>>> a = np.array([[1.,  2., np.nan],
                  [4.,  5.,  6.],
                  [np.nan, np.nan, 9.]])
>>> v = np.array([3, 7, 8])
>>> np.where(np.isnan(a), v, a)
array([[ 1.,  2.,  8.],
       [ 4.,  5.,  6.],
       [ 3.,  7.,  9.]])

numpy.isnan() gives you an array of booleans with NaN having the value True and False otherwise.

Your Answer

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.