简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM