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.
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
To access all elements between two indices
j you can use slicing:
slice_of_array = array[i: j+1] # use j if you DO NOT want index j included
import numpy as np mean_of_slice = np.mean(slice_of_array)
or all in one go (using your indices):
i = 3 j = 10 np.mean(array[i: j+1])