Tom
Tom

Reputation: 132

Select first occurrences after NaNs in Numpy array based on condition

I am quite new to Python and Numpy. Can someone help me to understand how I can solve the problem here expose? I have the following 2D array (arr) with NaNs and numbers, here below:

arr = np.array([[np.nan, 2.3, np.nan, np.nan, np.nan, 6.4, np.nan],
             [np.nan, np.nan, 3.1, 3.4, np.nan, np.nan, 3.9]])

I need to obtain a new array (result) with first occurrences no-NaN of the second row in arr contidioned by first occurrences no-NaN of the first row in arr; the rest all NaNs. Below what should be the result:

result = np.array([np.nan, np.nan, 3.1, np.nan, np.nan, np.nan, 3.9])

Many thanks in advance.

Upvotes: 0

Views: 57

Answers (1)

sai
sai

Reputation: 1784

Every first occurrence of a number in the second array after the occurrence of a num in the first array-

import numpy as np

#arr = np.array([[np.nan, 2.3, np.nan, np.nan, np.nan, 6.4, np.nan],
#                [np.nan, np.nan, 3.1, 3.4, np.nan, np.nan, 3.9]])

arr = np.array([[np.nan, 2.3, np.nan, np.nan, np.nan, 6.4, np.nan],
                [3, np.nan, np.nan, 3.1, 3.4, np.nan, np.nan]])

result = np.full_like(arr[1, :], np.nan)

arr1pos = np.squeeze(np.argwhere(np.isfinite(arr[0, :])))
arr2pos = np.squeeze(np.argwhere(np.isfinite(arr[1, :])))

first_occurrence_idxs = np.searchsorted(arr2pos, arr1pos)
if first_occurrence_idxs[-1] == arr2pos.size:
    result[arr2pos[first_occurrence_idxs[:-1]]] = arr[1, :][arr2pos[first_occurrence_idxs[:-1]]]
else:
    result[arr2pos[first_occurrence_idxs]] = arr[1, :][arr2pos[first_occurrence_idxs]]
print(result)
[nan nan nan 3.1 nan nan nan]

Upvotes: 0

Related Questions