[英]Numpy 1d Array CumSquare of the values
I am looking to emulate the functionality of numpy.cumsum()
, except I need to capture the cumulative squares of the values. 我想模仿
numpy.cumsum()
的功能,除了我需要捕获值的累积平方。
For example: I have an array that is [1,2,3,4]. 例如:我有一个[1,2,3,4]数组。
I can use numpy.cumsum(array)
to return an array([1,3,6,10])
. 我可以使用
numpy.cumsum(array)
返回一个array([1,3,6,10])
。 My goal is to use some fast numpy trick to get the cumulative squares of the values. 我的目标是使用一些快速的numpy技巧来获得值的累积平方。
In pure Python using a list: 在纯Python中使用列表:
>>> y = [1,2,3,4]
>>> sqVal = 0
>>> for val in y:
... sqVal += val*val
... print sqVal
...
1
5
14
30
I tried numpy.cumprod()
, but that is cumulative product, not the sum of the cumulative squares of the values. 我尝试了
numpy.cumprod()
,但这是累积产品,而不是值的累积平方和。 My desire to use NumPy is purely based on speed. 我使用NumPy的愿望完全基于速度。 Using
cumsum()
is substantially faster than using for loops (which makes sense). 使用
cumsum()
比使用for循环要快得多(这很有意义)。
Use numpy's square
function in addition to cumsum
: 除了
cumsum
之外还使用numpy的square
函数:
In [1]: import numpy as np
In [2]: a = np.array([1,2,3,4])
In [3]: np.square(a)
Out[3]: array([ 1, 4, 9, 16])
In [4]: np.cumsum(np.square(a))
Out[4]: array([ 1, 5, 14, 30])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.