Numpy: Diff on non-adjacent values

可紊 提交于 2021-01-28 09:42:07

问题


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

timeline = np.array([ 0, np.nan, np.nan, 4, np.nan, 6, np.nan, np.nan, 9, np.nan, 11, 12]) 

or like

timeline = np.array([ 0,  0,  0,  4,  0,  6,  0,  0,  9,  0, 11, 12])

The desired result should look like: (size of array is intact and position is important)

diff = np.array([ 0,  0,  0,  4,  0,  2,  0,  0,  3,  0, 2, 1])

np.diff returns the difference of adjacent values, and utilising NaN values to "force" it to use last "good" value, does not work.

Is there a simple way to do this?


回答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.



来源:https://stackoverflow.com/questions/61334602/numpy-diff-on-non-adjacent-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!