Pregunta

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

¿Fue útil?

Solución

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])
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top