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 only 6 values in the new list as there are only 18 elements in the first.
I am looking for an elegant way to do this with a minimal number of steps for a large list.
You can take a slice of
first
using for loop that iterates in 3 intervalHeres a solution using
pandas
withgroupby
:Using
numpy
, you can reshape your list of 18 elements into an array of shape(6, 3)
and then take the mean over the rowsThe use of
-1
innp.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 appropriatelyHere's another solution using
statistics.mean()
to get the mean of each chunk of every three numbers in the list.