Numpy: Computing sum(array[i, a[i]:b[i]]) for all rows i
<p>I have a numpy array <code>arr</code> and a list of slice start points <code>start</code> and a list of slice endpoints <code>end</code>. For each row <code>i</code>, I want to determine the sum of the elements from <code>start[i]</code> to <code>end[i]</code>. That is, I want to determine</p>

<pre><code>[np.sum(arr[i, start[i]:end[i]]) for i in range(arr.shape[0])]
</code></pre>

<p>Is there a smarter/faster way to do this using numpy only?</p>

<p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p>

<pre><code># Create range array corresponding to the length of the no. of cols
r = np.arange(arr.shape[1])

# Mask of ranges corresponding to the start and end indices using broadcasting
mask = (start[:,None] &lt;= r) &amp; (end[:,None] &gt; r)

# Finally, we use the mask to select and sum rows using einsum
out = np.einsum('ij,ij-&gt;i',arr,mask)
</code></pre>

python arrays numpy sum slice