简体   繁体   中英

Numpy : Calculating the average of values between two indices

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 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])
import numpy as np

np.mean(yourarray[3:11])

Assumed your array name is "yourarray"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM