What is the inverse of the numpy cumsum function?

為{幸葍}努か 提交于 2019-11-30 22:05:47

问题


If I have z = cumsum( [ 0, 1, 2, 6, 9 ] ), which gives me z = [ 0, 1, 3, 9, 18 ], how can I get back to the original array [ 0, 1, 2, 6, 9 ] ?


回答1:


z[1:] -= z[:-1].copy()

Short and sweet, with no slow Python loops. We take views of all but the first element (z[1:]) and all but the last (z[:-1]), and subtract elementwise. The copy makes sure we subtract the original element values instead of the values we're computing. (On NumPy 1.13 and up, you can skip the copy call.)




回答2:


You can use np.diff to compute elements 1...N which will take the difference between any two elements. This is the opposite of cumsum. The only difference is that diff will not return the first element, but the first element is the same in the original and cumsum output so we just re-use that value.

orig = np.insert(np.diff(z), 0, z[0])

Rather than insert, you could also use np.concatenate

orig = np.concatenate((np.array(z[0]).reshape(1,), np.diff(z)))

We could also just copy and replace elements 1...N

orig = z.copy()
orig[1:] = np.diff(z)



回答3:


If you want to keep z, you can use np.ediff1d:

x = np.ediff1d(z, to_begin=z[0])



回答4:


My favorite:

orig = np.r_[z[0], np.diff(z)]


来源:https://stackoverflow.com/questions/38666924/what-is-the-inverse-of-the-numpy-cumsum-function

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