Home > Software engineering >  Measure the average of elements of a 2d list with the same index in python
Measure the average of elements of a 2d list with the same index in python

Time:05-18

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?

CodePudding user response:

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]

CodePudding user response:

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.

  • Related