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
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.
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.
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.
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)))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With