numpy cumsum函数的逆是什么? [英] What is the inverse of the numpy cumsum function?

查看:345
本文介绍了numpy cumsum函数的逆是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有z = cumsum( [ 0, 1, 2, 6, 9 ] ),这给了我z = [ 0, 1, 3, 9, 18 ],如何返回原始数组[ 0, 1, 2, 6, 9 ]?

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 ] ?

推荐答案

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

又简短又甜美,没有缓慢的Python循环.我们对除第一个元素(z[1:])以外的所有元素和除最后一个元素(z[:-1])以外的所有元素进行查看,并逐元素相减.该副本可确保我们减去原始元素值,而不是我们正在计算的值. (在NumPy 1.13及更高版本上,则可以跳过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.)

这篇关于numpy cumsum函数的逆是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆