Ashok Kumar Jayaraman
Ashok Kumar Jayaraman

Reputation: 3085

How to calculate mean of columns from array lists in python using numpy?

I am trying to calculate the mean average of columns from a list of arrays.

f1_score = [array([0.807892  , 0.91698113, 0.73846154]),
            array([0.80041797, 0.9056244 , 0.72017837]),
            array([0.80541103, 0.91493384, 0.70282486])]

I also tried as mentioned below, but I couldn't get the mean value for columns.

output = []
for i in range(len(f1_score)): 
   output.append(np.mean(f1_score[i], axis = 0))

I get the mean values for rows:

[0.8211115582302323, 0.8087402497928408, 0.8077232421210242]

But I need the mean values for columns:

array([0.8045736667, 0.9125131233, 0.7204882567])

Thanks in advance for your answer.

Upvotes: 2

Views: 12538

Answers (3)

Ajith
Ajith

Reputation: 9

Try this:

f1_score = [[0.807892  , 0.91698113, 0.73846154],[0.80041797, 0.9056244 ,0.72017837],[0.80541103, 0.91493384, 0.70282486]]
temp=[]
output = []
for i in range(len(f1_score)):
    for j in range(len(f1_score)):
        temp.append(f1_score[j][i])
    output.append(np.mean(temp))
print(output)

Upvotes: 0

Clock Slave
Clock Slave

Reputation: 7967

If you dont mind using numpy you can do the following

import numpy as np
arr = np.random.randint(0,10,size=(2,2)) #sample data
arr
#array([[0, 2],
#       [6, 1]])
arr.mean(axis=0) #mean along the columns
# array([3. , 1.5])
arr.mean(axis=1) #mean along the rows
# array([1. , 3.5])

Alternatively, you can find the means by doing the following

arr = [[0,2], [6,1]]
col_means = [sum(i)/len(i) for i in zip(*arr)] #column wise means
# [3.0, 1.5]
row_means = [sum(i)/len(i) for i in arr] #row wise means
# [1.0, 3.5]

Upvotes: 1

WingedRasengan927
WingedRasengan927

Reputation: 150

You can use numpy's mean function and set the axis as 0.

mean(f1_score, axis=0)

And then you get the required answer

array([0.80457367, 0.91251312, 0.72048826])

Upvotes: 4

Related Questions