'Measure the average of elements of a 2d list with the same index in python
for example I have the following list
lst = [['1', '2', '3'], ['4', '5', '6'],['7', '8', '9']]
I want to find the average of 1+4+7, 2+5+8 and 3+6+9 Any idea on how to create such a function?
Solution 1:[1]
You can use a simple list comprehension:
lst = [['1', '2', '3'], ['4', '5', '6'],['7', '8', '9']]
from statistics import mean
out = [mean(map(int, x)) for x in zip(*lst)]
Output: [4, 5, 6]
Solution 2:[2]
By converting the list to float (or int) typed NumPy array and averaging on the expected axis using np.average:
np.average(np.asarray(lst, dtype=np.float64), axis=0)
# [4. 5. 6.]
This method is Just by NumPy, and no loops, so will be faster than loops on large arrays.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
| Solution 2 |
