Home > Blockchain >  How to calculate the avearge of every 4 elements in numpy array
How to calculate the avearge of every 4 elements in numpy array

Time:10-31

sample_list = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])

Required to take the average of every 4 
like 1,2,3,4 average is 2.5
followed by 5,6,7,8 is 6.5
followed by 9,10,11,12 is 10.5
followed by 13,14,15,16 is 14,5

expexted output:

[2.5, 6.5, 10.5, 14.5]

so far i tried with refering this questions Average of each consecutive segment in a list

Calculate the sum of every 5 elements in a python array

CodePudding user response:

Use reshape. In following example reshape(-1, 4) means 4 elements per row

import numpy as np

sample_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])

print(np.mean(sample_list.reshape(-1, 4), axis=1))

output

[2.5, 6.5, 10.5, 14.5]

CodePudding user response:

There are various ways to do that. Considering that sample_list looks like the following

sample_list = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])

[Out]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])

Will leave below two options that will allow one to calculate the average of every 4 elements in the numpy array.


Option 1

newlist = [sum(sample_list[i:i 4])/4 for i in range(0, len(sample_list), 4)]

[Out]: [2.5, 6.5, 10.5, 14.5]

Option 2

Using numpy.mean

newlist = [np.mean(sample_list[i:i 4]) for i in range(0, len(sample_list), 4)]

[Out]: [2.5, 6.5, 10.5, 14.5]
  • Related