Home > Software engineering >  numpy - Subtract array between actual value and previous value (only not null)
numpy - Subtract array between actual value and previous value (only not null)

Time:05-12

I have the following situation:

Supposing I have an array, and I want to subtract (absolute value) between the actual not null value and the previous not null values.

[np.nan, np.nan, 10, np.nan, np.nan, 5, np.nan, 3, 6, np.nan, np.nan, 7]

Expected output:

[nan, nan, nan, nan, nan, 5, nan, 2, 3, nan, nan, 1]

What is a good approach to get this result using numpy without for loops?

I only solved it using for loop:

x = [np.nan, np.nan, 10, np.nan, np.nan, 5, np.nan, 3, 6, np.nan, np.nan, 7]
idx = np.where(~np.isnan(x))[0]
output = np.full(len(x), np.nan)

for i, j in enumerate(idx):
  if i > 0:
   output[j] = abs(x[idx[i]] - x[idx[i - 1]])

CodePudding user response:

You're most of the way there already:

output[idx[1:]] = np.abs(np.diff(x[idx]))
  • Related