I have two arrays, arr1 and arr2, same length contain random NaNs and numbers.

arr1 = np.array((1.3, -1.2, -0.2, 1.6, np.nan, np.nan, np.nan)) arr2 = np.array((-0.6, np.nan, 2.3, np.nan, -2.4, np.nan, 1.2))

I need to obtain a third array where:

- the lenght is the same of the others.
- firstvalue (1.3): is the first not nan value of the first array.
- secondvalue (2.3): is the first no nan value of the second array at index higher of the firstvalue(1.3).
- thirdvalue (1.6): is the second no nan value of the first array at index higher of the secondvalue(2.3).
- repeat steps 3 and 4 till to the end of the array.

Below what should be the third array result:

result = np.array((1.3, np.nan, 2.3, 1.6, -2.4, np.nan, np.nan))

## Answer

I think a for loop is not too bad (and seemingly unavoidable) in this case:

arrs = [arr1, arr2] out = [0.0] * len(arr1) # indicate which array we are working on curr_arr = 0 for i in range(len(arr1)): # copy the current head element to `out` out[i] = arrs[curr_arr][i] # if the current element is not nan # switch the active array if not np.isnan(out[i]): curr_arr = 1 - curr_arr

Output:

[1.3, nan, 2.3, 1.6, -2.4, nan, nan]