Is there a simple way to calculate the mean of several (same length) lists in Python? Say, I have [[1, 2, 3], [5, 6, 7]]
, and want to obtain [3,4,5]
. This is to be doing 100000 times, so want it to be fast.
In case you're using numpy
(which seems to be more appropriate here):
>>> import numpy as np
>>> data = np.array([[1, 2, 3], [5, 6, 7]])
>>> np.average(data, axis=0)
array([ 3., 4., 5.])
In [6]: l = [[1, 2, 3], [5, 6, 7]]
In [7]: [(x+y)/2 for x,y in zip(*l)]
Out[7]: [3, 4, 5]
(You'll need to decide whether you want integer or floating-point maths, and which kind of division to use.)
On my computer, the above takes 1.24us:
In [11]: %timeit [(x+y)/2 for x,y in zip(*l)]
1000000 loops, best of 3: 1.24 us per loop
Thus processing 100,000 inputs would take 0.124s.
Interestingly, NumPy arrays are slower on such small inputs:
In [27]: In [21]: a = np.array(l)
In [28]: %timeit (a[0] + a[1]) / 2
100000 loops, best of 3: 5.3 us per loop
In [29]: %timeit np.average(a, axis=0)
100000 loops, best of 3: 12.7 us per loop
If the inputs get bigger, the relative timings will no doubt change.
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