Firat.Berk.Cakar - 1 year ago 76

Python Question

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

Answer Source

To access all elements between two indices `i`

and `j`

you can use slicing:

```
slice_of_array = array[i: j+1] # use j if you DO NOT want index j included
```

and the average is calculated with `np.average`

, but in your case you want to weight with the number of elements, so you can just use the `np.mean`

:

```
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])
```