Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mean over multiple axis in NumPy

I Want to write the code below as Pythonic way, applying mean over two axis. What the best way to do this?

import numpy as np

m = np.random.rand(30, 10, 10)  
m_mean = np.zeros((30, 1))    
for j in range(30):
    m_mean[j, 0] = m[j, :, :].mean()
like image 296
marcelorodrigues Avatar asked Nov 05 '15 18:11

marcelorodrigues


People also ask

Is there a mean function in NumPy?

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis.

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

What does 3 mean in NumPy?

The 3 is part of that shape tuple. You will reference the dimensions by number in subsequent numpy code. arr. shape[2] will return 3 , and arr[:,:,0] will be all the R values of the image (if that is the correct interpreation).


1 Answers

If you have a sufficiently recent NumPy, you can do

m_mean = m.mean(axis=(1, 2))

I believe this was introduced in 1.7, though I'm not sure. The documentation was only updated to reflect this in 1.10, but it worked earlier than that.

If your NumPy is too old, you can take the mean a bit more manually:

m_mean = m.sum(axis=2).sum(axis=1) / np.prod(m.shape[1:3])

These will both produce 1-dimensional results. If you really want that extra length-1 axis, you can do something like m_mean = m_mean[:, np.newaxis] to put the extra axis there.

like image 114
user2357112 supports Monica Avatar answered Sep 17 '22 01:09

user2357112 supports Monica