Mode / Med / Medium for numpy 3D matrix

I have a 3d numpy array and my goal is to get the average / mode / median.

It has the form [500,300,3]

And I would like to get, for example:

[430,232,22] As a mode

Is there any way to do this? The standard np.mean (array) gives me a very large array.

I donโ€™t know if this is really correct?

weather_image.mean(axis=0).mean(axis=0) 

It gives me a 1d np array of length 3

+4
python numpy scipy
source share
1 answer

You want to get average / median / mode along the first two axes . This should work:

 data = np.random.randint(1000, size=(500, 300, 3)) >>> np.mean(data, axis=(0, 1)) # in nunpy >= 1.7 array([ 499.06044 , 499.01136 , 498.60614667]) >>> np.mean(np.mean(data, axis=0), axis=0) # in numpy < 1.7 array([ 499.06044 , 499.01136 , 498.60614667]) >>> np.median(data.reshape(-1, 3), axis=0) array([ 499., 499., 498.]) # mode >>> np.argmax([np.bincount(x) for x in data.reshape(-1, 3).T], axis=1) array([240, 519, 842], dtype=int64) 

Note that np.median requires a flattened array, hence a change. And bincount only handles 1D inputs, hence list comprehension, coupled with a little transpositional magic to unpack.

+5
source share

All Articles