How can I find the final cumulative sum across num

2020-04-10 14:30发布

I have a numpy array

np.array(data).shape 
(50,50)

Now, I want to find the cumulative sums across axis=1. The problem is cumsum creates an array of cumulative sums, but I just care about the final value of every row.

This is incorrect of course:

np.cumsum(data, axis=1)[-1]

Is there a succinct way of doing this without looping through the array.

标签: python numpy
3条回答
相关推荐>>
2楼-- · 2020-04-10 15:10

The final cumulative sum of every row, is in fact simply the sum of every row, or the row-wise sum, so we can implement this as:

>>> x.sum(axis=1)
array([ 10,  35,  60,  85, 110])

So here for every row, we calculate the sum of all the columns. We thus do not need to first generate the sums in between (well these will likely be stored in an accumulator in numpy), but not "emitted" in the array.

查看更多
虎瘦雄心在
3楼-- · 2020-04-10 15:19

You are almost there, but as you have it now, you are selecting just the final row. What you need is to select all rows from the last column, so your indexing at the end should be: [:,-1].

Example:

>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

>>> a.cumsum(axis=1)[:,-1]
array([ 10,  35,  60,  85, 110])

Note, I'm leaving this up as I think it explains what was going wrong with your attempt, but admittedly, there are more effective ways of doing this in the other answers!

查看更多
神经病院院长
4楼-- · 2020-04-10 15:22

You can use numpy.ufunc.reduce if you don't need the intermediary accumulated results of any ufunc.

>>> a = np.arange(9).reshape(3,3)
>>> a
>>> 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> 
>>> np.add.reduce(a, axis=1)
>>> array([ 3, 12, 21])

However, in the case of sum, Willem's answer is clearly superior and to be preferred. Just keep in mind that in the general case, there's ufunc.reduce.

查看更多
登录 后发表回答