Multiple cumulative sum within a numpy array

混江龙づ霸主 提交于 2019-12-01 10:53:54

Not sure about numpy, but pandas can do this pretty easily with a groupby + cumsum:

import pandas as pd

s = pd.Series(my_vector)
s.groupby(s.index.isin(size_of_groups.cumsum()).cumsum()).cumsum()

0    1
1    3
2    6
3    4
4    9
dtype: int64

Here's a vectorized solution -

def intervaled_cumsum(ar, sizes):
    # Make a copy to be used as output array
    out = ar.copy()

    # Get cumumlative values of array
    arc = ar.cumsum()

    # Get cumsumed indices to be used to place differentiated values into
    # input array's copy
    idx = sizes.cumsum()

    # Place differentiated values that when cumumlatively summed later on would
    # give us the desired intervaled cumsum
    out[idx[0]] = ar[idx[0]] - arc[idx[0]-1]
    out[idx[1:-1]] = ar[idx[1:-1]] - np.diff(arc[idx[:-1]-1])
    return out.cumsum()

Sample run -

In [114]: ar = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
     ...: sizes = np.array([3,2,2,3,2])

In [115]: intervaled_cumsum(ar, sizes)
Out[115]: array([ 1,  3,  6,  4,  9,  6, 13,  8, 17, 27, 11, 23])

Benchmarking

Other approach(es) -

# @cᴏʟᴅsᴘᴇᴇᴅ's solution
import pandas as pd
def pandas_soln(my_vector, sizes):
    s = pd.Series(my_vector)
    return s.groupby(s.index.isin(sizes.cumsum()).cumsum()).cumsum().values

The given sample used two intervals of lengths 2 and 3 Keeping that and simply giving it more number of groups for timing purpose.

Timings -

In [146]: N = 10000 # number of groups
     ...: np.random.seed(0)
     ...: sizes = np.random.randint(2,4,(N))
     ...: ar = np.random.randint(0,N,sizes.sum())

In [147]: %timeit intervaled_cumsum(ar, sizes)
     ...: %timeit pandas_soln(ar, sizes)
10000 loops, best of 3: 178 µs per loop
1000 loops, best of 3: 1.82 ms per loop

In [148]: N = 100000 # number of groups
     ...: np.random.seed(0)
     ...: sizes = np.random.randint(2,4,(N))
     ...: ar = np.random.randint(0,N,sizes.sum())

In [149]: %timeit intervaled_cumsum(ar, sizes)
     ...: %timeit pandas_soln(ar, sizes)
100 loops, best of 3: 3.91 ms per loop
100 loops, best of 3: 17.3 ms per loop

In [150]: N = 1000000 # number of groups
     ...: np.random.seed(0)
     ...: sizes = np.random.randint(2,4,(N))
     ...: ar = np.random.randint(0,N,sizes.sum())

In [151]: %timeit intervaled_cumsum(ar, sizes)
     ...: %timeit pandas_soln(ar, sizes)
10 loops, best of 3: 31.6 ms per loop
1 loop, best of 3: 357 ms per loop

Here is an unconventional solution. Not very fast, though. (Even a bit slower than pandas).

>>> from scipy import linalg
>>> 
>>> N = len(my_vector)
>>> D = np.repeat((*zip((1,-1)),), N, axis=1)
>>> D[1, np.cumsum(size_of_groups) - 1] = 0
>>> 
>>> linalg.solve_banded((1, 0), D, my_vector)
array([1., 3., 6., 4., 9.])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!