Jzl5325
Jzl5325

Reputation: 3974

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.

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).

Upvotes: 1

Views: 457

Answers (1)

Wilduck
Wilduck

Reputation: 14126

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

Upvotes: 3

Related Questions