Skip to content
Advertisement

How would I sort averages by row and/or column of an array?

I’ve been having trouble with finding the average of an array of lists, specifically by row and by column. I know what I want to do with it, but I’m struggling with finding what kind of code to write for it. The array is as follows:

data = [[126, 91, 43],
[534, 59, 148],
[53, 78, 1],
[725, 727, 729],
[0, 12, 0],
[64, 23, 3]]

By row, I want to essentially find the averages of each individual list within this array without combining them. By column, I want to find the averages of the x’th item in each list within the array. What I want to code is as follows: By row: find how many lists there are in the array, then calculate their means individually. The index range would be unlimited. By column: find how many lists there are in the array, take only the x’th terms from each list, and calculate their means. The index range would be unlimited. Any help is appreciated.

Advertisement

Answer

import statistics

data = [
    [126, 91, 43],
    [534, 59, 148],
    [53, 78, 1],
    [725, 727, 729],
    [0, 12, 0],
    [64, 23, 3],
]

row_average = [statistics.fmean(x) for x in data]
print(row_average)  # [86.66666666666667, 247.0, 44.0, 727.0, 4.0, 30.0]
column_average = [statistics.fmean(x) for x in zip(*data)]
print(column_average)  # [250.33333333333334, 165.0, 154.0]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement