3

I have 2 Numpy arrays with the same length

array([ 0.9737068 , NaN, NaN, ..., -0.64236529,
 -0.88137541, -0.78318609])
array([ 0.9 , 0.7643, 0.61, ..., -0.64236529,
 -0.88137541, -0.78318609])

In the first array I have NaN values, how can I replace these NaN values with values from the second array. In this example my third array would be:

array([ 0.9737068 , Nan => 0.7643, NaN => 0.61 , ..., -0.64236529,
 -0.88137541, -0.78318609])
David Buck
3,88640 gold badges54 silver badges74 bronze badges
asked Mar 28, 2020 at 18:28
1
  • Do you want a new array or to replace one of them? Commented Mar 28, 2020 at 18:33

4 Answers 4

6

Using Numpy, the following works by applying a Boolean mask to both arrays:

import numpy as np
x = np.array([0.9737068, np.nan, np.nan, -0.64236529, -0.88137541, -0.78318609])
y = np.array([0.9, 0.7643, 0.61, -0.64236529, -0.88137541, -0.78318609])
x[np.isnan(x)] = y[np.isnan(x)]

Results in

In[1]: x
Out[1]: 
array([ 0.9737068 , 0.7643 , 0.61 , -0.64236529, -0.88137541,
 -0.78318609])

N.B. Running with %timeit, this solution takes < 4μs in repeated runs, vs. the other two Numpy solutions (at time of writing this) which both take 20-25μs

answered Mar 28, 2020 at 18:39
Sign up to request clarification or add additional context in comments.

Comments

1

Pythonic solution:

import numpy as np
def no_nans_arrays(array_w_nans,array_no_nans):
 return np.array([array_w_nans[i] if not np.isnan(array_w_nans[i]) else array_no_nans[i] for i in range(len(array_w_nans))])
answered Mar 28, 2020 at 18:38

Comments

0

If not numpy, you might find this function helpful:

def swap(A,B,i,j):
 TEMP_B = B[j]
 B[j] = A[i]
 A[i] = TEMP_B
 return A,B

Iterate over your first array, if element is NaN, then use swap.

Taken from this question.

answered Mar 28, 2020 at 18:33

Comments

0
res = np.array([ a1 if not np.isnan(a1) else b1 for a1,b1 in zip(a, b) ])

np.isnan returns False if the given element in the np.array is np.NaN

answered Mar 28, 2020 at 18:46

1 Comment

a more Pythonic solution would be if not np.isnan(a1) instead of if np.isnan(a1)==False

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.