Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

numpy – Subtract array between actual value and previous value (only not null)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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]])

>Solution :

You’re most of the way there already:

output[idx[1:]] = np.abs(np.diff(x[idx]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading