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>You need to mask the original array so only the non-zero elements are overwritten:</p>

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

Out[9]:
array([ 1,  3,  4,  6, 11,  0, 20, 26,  0, 28, 31,  0])
</code></pre>

<p>Another method is to use <code>np.where</code>:</p>

<pre><code>In [93]:
a = np.array([1,2,1,2,5,0,9,6,0,2,3,0])
a = np.where(a!=0,np.cumsum(a),a)
a

Out[93]:
array([ 1,  3,  4,  6, 11,  0, 20, 26,  0, 28, 31,  0])
</code></pre>

<p><strong>timings</strong></p>

<pre><code>In [91]:
%%timeit
a = np.array([1,2,1,2,5,0,9,6,0,2,3,0])
a[a!=0] = np.cumsum(a[a!=0])
a

The slowest run took 4.93 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 12.6 Âµs per loop

In [94]:    
%%timeit
a = np.array([1,2,1,2,5,0,9,6,0,2,3,0])
a = np.where(a!=0,np.cumsum(a),a)
a

The slowest run took 6.00 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 10.5 Âµs per loop
</code></pre>

<p>the above shows that <code>np.where</code> is marginally quicker than the first method</p>

python numpy