Skip to content Skip to sidebar Skip to footer

How To Calculate Mean Of Every Three Values Of A List

I have a list: first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] I want another list with mean of three values and so the new list be: new = [2,5,8,11,14,17] There will be

Solution 1:

Using numpy, you can reshape your list of 18 elements into an array of shape (6, 3) and then take the mean over the rows

import numpy as np
a = np.array(first)

>>> a.reshape(-1, 3)
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12],
       [13, 14, 15],
       [16, 17, 18],

>>> a.reshape(-1, 3).mean(axis=1)
array([ 2.,  5.,  8., 11., 14., 17.])

The use of -1 in np.reshape(-1, 3) actually allows you to use this approach for any array whose size is a multiple of 3 and it will automatically size the first dimension appropriately

Solution 2:

Heres a solution using pandas with groupby:

import pandas as pd

ser = pd.Series(first)
ser.groupby(ser.index//3).mean()021528311414517
dtype: int64

Solution 3:

You can take a slice of first using for loop that iterates in 3 interval

import statistics

new = [statistics.mean(first[i:i + 3]) for i in range(0, len(first), 3)]
print(new) # [2, 5, 8, 11, 14, 17]

Solution 4:

Here's another solution using statistics.mean() to get the mean of each chunk of every three numbers in the list.

>>>from statistics import mean>>>first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]>>>[mean(x) for x inzip(*[iter(first)] * 3)]
[2, 5, 8, 11, 14, 17]

Post a Comment for "How To Calculate Mean Of Every Three Values Of A List"