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.
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:
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.
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:
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!
You can use
numpy.ufunc.reduce
if you don't need the intermediary accumulated results of anyufunc
.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'sufunc.reduce
.