Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.