Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the mean of multiple axis of a numpy array

Tags:

In numpy is there a fast way of calculating the mean across multiple axis? I am calculating the mean on all but the 0 axis of an n-dimensional array.

I am currently doing this;

for i in range(d.ndim - 1):     d = d.mean(axis=1) 

I'm wondering if there is a solution that doesn't use a python loop.

like image 472
dsg101 Avatar asked Jul 01 '13 03:07

dsg101


People also ask

How do you average multiple Numpy arrays?

Finding average of NumPy arrays is quite similar to finding average of given numbers. We just have to get the sum of corresponding array elements and then divide that sum with the total number of arrays.

What is the difference between NP mean and NP average?

np. mean always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result). np. average can compute a weighted average if the weights parameter is supplied.

How do you find the average of a 2D array in Python?

To calculate the average separately for each column of the 2D array, use the function call np. average(matrix, axis=0) setting the axis argument to 0. What is this? The resulting array has three average values, one per column of the input matrix .


1 Answers

In numpy 1.7 you can give multiple axis to np.mean:

d.mean(axis=tuple(range(1, d.ndim))) 

I am guessing this will perform similarly to the other proposed solutions, unless reshaping the array to flatten all dimensions triggers a copy of the data, in which case this should be much faster. So this is probably going to give a more consistent performance.

like image 151
Jaime Avatar answered Oct 20 '22 06:10

Jaime