Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

averaging list of lists python column-wise

Tags:

python

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

like image 749
frazman Avatar asked Jun 06 '12 18:06

frazman


People also ask

How do you take the average of multiple lists in Python?

Calculating the average of different values in Python is very straightforward. You simply add up an array of numbers and divide it by the length of that array.

How do you average a list of values?

The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list.

How do you find the average of a 2D list?

To calculate the average of each cell, all that is needed is to obtain the values of all numeric cells within the 2D list, and then to sum the contents of those numeric values and divide by the quantity of numeric values.


2 Answers

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))) 
like image 194
Sven Marnach Avatar answered Oct 01 '22 06:10

Sven Marnach


data = [[240, 240, 239],         [250, 249, 237],          [242, 239, 237],         [240, 234, 233]] avg = [float(sum(col))/len(col) for col in zip(*data)] # [243.0, 240.5, 236.5] 

This works because zip(*data) will give you a list with the columns grouped, the float() call is only necessary on Python 2.x, which uses integer division unless from __future__ import division is used.

like image 27
Andrew Clark Avatar answered Oct 01 '22 06:10

Andrew Clark