Skip to content Skip to sidebar Skip to footer

Numpy: Diff On Non-adjacent Values

I'd like to take the difference of non-adjacent values within a 1D numpy array. The array is a selection of values along a timeline from 1 to N. For N=12, the array could look like

Solution 1:

Use lists of indices. I'm assuming you want to keep the first value as-is.

For zero spacers:

imask = np.flatnonzero(timeline)
diff = np.zeros_like(timeline)
diff[imask[0]] = timeline[imask[0]]
diff[imask[1:]] = timeline[imask[1:]] - timeline[imask[:-1]]

Or more elegantly, replace the last two lines with:

diff[imask] = np.diff(timeline[imask], prepend=0)

For nans just replace the first line with

imask = np.flatnonzero(~np.isnan(timeline))

If you have access to the original mask used to make the selection, all the better. Use it as the argument to flatnonzero instead.

Post a Comment for "Numpy: Diff On Non-adjacent Values"