Home > Software engineering >  How would I sort averages by row and/or column of an array?
How would I sort averages by row and/or column of an array?

Time:10-24

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.

CodePudding user response:

For row wise

[sum(i)/len(i) for i in data]

For colum wise

[sum(i)/len(i) for i in zip(*data)]

CodePudding user response:

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]

CodePudding user response:

from statistics import mean

print(*map(mean, zip(*data)))

Output

250.33333333333334 165 154

or else

avg_each_list = [float(sum(data))/len(data) for data in zip(*data)]
print(avg_each_list )

output

[250.33333333333334, 165.0, 154.0]
  • Related