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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With