I have an array of varying size from which I would like to average each consecutive n numbers and build another array as a result.
I have come up with two different ways but each have their problems and I am not sure if this is the best way to solve this:
Using numpy.array_split() function:
import numpy as np no_splits = 3 #Or any number user defines no_items = int(np.random.random(1)*100) # To get a variable number of items pre_array = np.random.random(no_items) mean_array = np.mean(np.array_split(pre_array,no_splits)) #This is efficient but gives an error if len(pre_array)%no_splits != 0enumerate(pre_array) alternative:
mean_array = [np.mean(pre_array[i-no_splits+1:i]) for i, x in enumerate(pre_array) if i%no_splits == 0 and i != 0]
This is fine but clips the last values if i%no_splits != 0. Ideally, I would create a last value that is the mean of the remaining ones whilst keeping the code compact.
Each of this works for my purposes but I am not sure if they are the most efficient for larger arrays.
Thank you in advance!
0 1 2and1 2 3... or0 1 2and3 4 5... from0 1 2 3 4...?