Bobesh Bobesh - 2 months ago 27
Python Question

Python numpy nonzero cumsum

I want to do nonzero

cumsum
with
numpy
array. Simply skip zeros in array and apply
cumsum
. Suppose I have a np. array

a = np.array([1,2,1,2,5,0,9,6,0,2,3,0])


my result should be

[1,3,4,6,11,0,20,26,0,28,31,0]


I have tried this

a = np.cumsum(a[a!=0])


but result is

[1,3,4,6,11,20,26,28,31]


Any ideas?

Answer

Just trying to simplify it:)

b=np.cumsum(a)
[b[i]  if ((i > 0 and b[i] != b[i-1]) or i==0) else 0 for i in range(len(b))]