Numpy : Calculating the average of values between two indices
<p>I need to calculate the average of values that are between 2 indices. Lets say my indices are 3 and 10, and i would like to sum up all the values between them and divide by the number of values.</p>

<p>Easiest way would be just using a for loop starting from 3, going until 10, summing 'em up, and dividing. This seems like a really non-pythonic way and considering the functionalities Numpy offers, i thought maybe there is a shorter way using some Numpy magic. Any suggestion is much appriciated</p>

<p>To access all elements between two indices <code>i</code> and <code>j</code> you can use slicing:</p>

<pre><code>slice_of_array = array[i: j+1] # use j if you DO NOT want index j included
</code></pre>

<p>and the average is calculated with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.average.html" rel="nofollow"><code>np.average</code></a>, but in your case you want to weight with the number of elements, so you can just use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html" rel="nofollow"><code>np.mean</code></a>:</p>

<pre><code>import numpy as np
mean_of_slice = np.mean(slice_of_array)
</code></pre>

<p>or all in one go (using your indices):</p>

<pre><code>i = 3
j = 10
np.mean(array[i: j+1])
</code></pre>

python python-3.x numpy