문제

I am looking to emulate the functionality of numpy.cumsum(), except I need to capture the cumulative squares of the values.

For example: I have an array that is [1,2,3,4].

I can use numpy.cumsum(array) to return an array([1,3,6,10]). My goal is to use some fast numpy trick to get the cumulative squares of the values.

In pure Python using a list:

>>> 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. My desire to use NumPy is purely based on speed. Using cumsum() is substantially faster than using for loops (which makes sense).

도움이 되었습니까?

해결책

Use numpy's square function in addition to cumsum:

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top