averaging list of lists python column-wise
python
Solution
Pure Python:
from __future__ import division
def mean(a):
return sum(a) / len(a)
a = [[240, 240, 239],
[250, 249, 237],
[242, 239, 237],
[240, 234, 233]]
print map(mean, zip(*a))
printing
[243.0, 240.5, 236.5]
NumPy:
a = numpy.array([[240, 240, 239],
[250, 249, 237],
[242, 239, 237],
[240, 234, 233]])
print numpy.mean(a, axis=0)
Python 3:
from statistics import mean
a = [[240, 240, 239],
[250, 249, 237],
[242, 239, 237],
[240, 234, 233]]
print(*map(mean, zip(*a)))
Problem
I have a list of lists: something like: ``` data = [[240, 240, 239], [250, 249, 237], [242, 239, 237], [240, 234, 233]] ``` And I want to average this out like ``` [average_column_1, average_column_2, average_column_3] ``` My piece of code is like not very elegant. It is the naive way of going thru the list, keeping the sum in seperate container and then dividing by number of elements. I think there is a pythonic way to do this. Any suggestions? Thanks