Meysam Meysam - 1 year ago 71
Python Question

Averaging over every n elements of an array without numpy

I have an array. I want to create a new array which is the average over every third element. So the new array will be a third of the size as the original.

As an example:


should return the array:


Can anyone suggest an efficient way of doing this? I want to do this without using numpy.

am2 am2
Answer Source

what is the problem?

a = [1,2,3,4,5,6,7,8,9]
def reduce_list(any_list, number_of_values_to_combine):
    ret_list = []
    for i in range(len(any_list)//number_of_values_to_combine):
        new_value = 0
        for j in range(number_of_values_to_combine):
            new_value += any_list[i*number_of_values_to_combine + j]
    return ret_list

print reduce_list(a,3)

rest will be ignored, if there are f.e. 7 elements combined to 3 there will be 2 elements in the result

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download