Bobesh - 1 month ago 5

Python Question

I want to do nonzero

`cumsum`

`numpy`

`cumsum`

`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))]
```

Source (Stackoverflow)

Comments