Python numpy nonzero cumsum
<p>I want to do nonzero <code>cumsum</code> with <code>numpy</code> array. Simply skip zeros in array and apply <code>cumsum</code>. Suppose I have a np. array </p>

<pre><code>a = np.array([1,2,1,2,5,0,9,6,0,2,3,0])
</code></pre>

<p>my result should be</p>

<pre><code>[1,3,4,6,11,0,20,26,0,28,31,0]
</code></pre>

<p>I have tried this</p>

<pre><code>a = np.cumsum(a[a!=0])
</code></pre>

<p>but result is</p>

<pre><code>[1,3,4,6,11,20,26,28,31]
</code></pre>

<p>Any ideas? </p>

<p>To my mind, jotasi's suggestion in a comment to the OP is the most idiomatic. Here are some timings, though note that Shawn. L's answer returns a Python list, not a NumPy array, so they are not strictly comparable.</p>

<pre><code>import numpy as np

def jotasi(a):
  b = np.cumsum(a)
  b[a==0] = 0
  return b

def EdChum(a):
  a[a!=0] = np.cumsum(a[a!=0])
  return a

def ShawnL(a):
  b=np.cumsum(a)
  b = [b[i]  if ((i &gt; 0 and b[i] != b[i-1]) or i==0) else 0 for i in range(len(b))]
  return b

def Ed2(a):
  return np.where(a!=0,np.cumsum(a),a)
</code></pre>

<p>To test, I generated a NumPy array of 1E5 integers in [0,100]. Therefore about 1% are 0. These results are from NumPy 1.9.2, Python 2.7.12, and are presented from slowest to fastest:</p>

<pre><code>import timeit
a = np.random.random_integers(0,100,100000)

len(a[a==0]) #verify there are some 0's
1003

timeit.timeit("ShawnL(a)", "from __main__ import a,EdChum,ShawnL,jotasi,Ed2", number=250)
11.743098020553589
timeit.timeit("EdChum(a)", "from __main__ import a,EdChum,ShawnL,jotasi,Ed2", number=250)
0.1794271469116211
timeit.timeit("Ed2(a)", "from __main__ import a,EdChum,ShawnL,jotasi,Ed2", number=250)
0.1282949447631836
timeit.timeit("jotasi(a)", "from __main__ import a,EdChum,ShawnL,jotasi,Ed2", number=250)
0.09286999702453613
</code></pre>

<p>I'm a little surprised there's such a big difference between jotasi's and Ed Chum's answers - minimizing boolean operations is noticeable I guess. No surprise that a list comprehension is slow.</p>

python numpy