Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate mean across dimension in a 2D array

I have an array a like this:

a = [[40, 10], [50, 11]] 

I need to calculate the mean for each dimension separately, the result should be this:

[45, 10.5] 

45 being the mean of a[*][0] and 10.5 the mean of a[*][1].

What is the most elegant way of solving this without using a loop?

like image 947
otmezger Avatar asked Apr 04 '13 19:04

otmezger


People also ask

How do you find the mean of a 2D array?

We can find out the mean of each row and column of 2d array using numpy with the function np. mean(). Here we have to provide the axis for finding mean.

How do you find the average of a 2D list?

To calculate the average of each cell, all that is needed is to obtain the values of all numeric cells within the 2D list, and then to sum the contents of those numeric values and divide by the quantity of numeric values.

How do you find the mean of an array?

Given an array, the task is to find average of that array. Average is the sum of array elements divided by the number of elements. Examples : Input : arr[] = {1, 2, 3, 4, 5} Output : 3 Sum of the elements is 1+2+3+4+5 = 15 and total number of elements is 5.

How do you find the mean of a column in a Numpy array?

1 Answer. You need to use Numpy function mean() with "axis=0" to compute average by column. To compute average by row, you need to use "axis=1". array([ 7., 8., 9., 10.])


1 Answers

a.mean() takes an axis argument:

In [1]: import numpy as np  In [2]: a = np.array([[40, 10], [50, 11]])  In [3]: a.mean(axis=1)     # to take the mean of each row Out[3]: array([ 25. ,  30.5])  In [4]: a.mean(axis=0)     # to take the mean of each col Out[4]: array([ 45. ,  10.5]) 

Or, as a standalone function:

In [5]: np.mean(a, axis=1) Out[5]: array([ 25. ,  30.5]) 

The reason your slicing wasn't working is because this is the syntax for slicing:

In [6]: a[:,0].mean() # first column Out[6]: 45.0  In [7]: a[:,1].mean() # second column Out[7]: 10.5 
like image 77
askewchan Avatar answered Oct 18 '22 13:10

askewchan