+2 votes
in Programming Languages by (20.3k points)
How can I compute the cumulative sum or product of elements of a Numpy matrix along a row or column? I do not want to use the "for" loop. Is there any function for it?

E.g.

matrix([[ 0,  1,  2,  3],

        [ 4,  5,  6,  7],

        [ 8,  9, 10, 11]])

Cumulative sum along row should be:

matrix([[ 0,  1,  2,  3],

        [ 4,  6,  8, 10],

        [12, 15, 18, 21]])

1 Answer

0 votes
by (36.1k points)

Numpy's functions cumsum() and cumprod() can be used for cumulative sum and product respectively. You can specify axis=0/1 (row/column) as a parameter of these functions.

Here is an example:

>>> import numpy as np
>>> bb = np.matrix(np.arange(12).reshape((3,4)))
>>> bb
matrix([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
>>> bb.cumsum(axis=0)
matrix([[ 0,  1,  2,  3],
        [ 4,  6,  8, 10],
        [12, 15, 18, 21]])
>>> bb.cumsum(axis=1)
matrix([[ 0,  1,  3,  6],
        [ 4,  9, 15, 22],
        [ 8, 17, 27, 38]])
>>> bb.cumprod(axis=0)
matrix([[  0,   1,   2,   3],
        [  0,   5,  12,  21],
        [  0,  45, 120, 231]])
>>> bb.cumprod(axis=1)
matrix([[   0,    0,    0,    0],
        [   4,   20,  120,  840],
        [   8,   72,  720, 7920]])

...