Find maximum 3D np.array along axis = 0

I have a 3D numpy array that looks like this:

X = [[[10 1] [ 2 10] [-5 3]] [[-1 10] [ 0 2] [ 3 10]] [[ 0 3] [10 3] [ 1 2]] [[ 0 2] [ 0 0] [10 0]]] 

First, I want the maximum along the axis to be zero using X.max (axis = 0)):

which gives me:

  [[10 10] [10 10] [10 10]] 

The next step is now my problem; I would like to name the location of every 10 and create a new 2D array from another three-dimensional array that has the same dimeons as X.

for example, an array with the same dimensions looks like this:

  Y = [[[11 2] [ 3 11] [-4 100]] [[ 0 11] [ 100 3] [ 4 11]] [[ 1 4] [11 100] [ 2 3]] [[ 100 3] [ 1 1] [11 1]]] 

I want to find the maximum location in X and create a 2D array of numbers and location in Y.

The answer in this case should be:

  [[11 11] [11 11] [11 11]] 

Thanks for your help in advance :)

+5
source share
2 answers

you can do this with numpy.argmax and numpy.indices .

 import numpy as np X = np.array([[[10, 1],[ 2,10],[-5, 3]], [[-1,10],[ 0, 2],[ 3,10]], [[ 0, 3],[10, 3],[ 1, 2]], [[ 0, 2],[ 0, 0],[10, 0]]]) Y = np.array([[[11, 2],[ 3,11],[-4, 100]], [[ 0,11],[ 100, 3],[ 4,11]], [[ 1, 4],[11, 100],[ 2, 3]], [[ 100, 3],[ 1, 1],[11, 1]]]) ind = X.argmax(axis=0) a1,a2=np.indices(ind.shape) print X[ind,a1,a2] # [[10 10] # [10 10] # [10 10]] print Y[ind,a1,a2] # [[11 11] # [11 11] # [11 11]] 

The answer here was an inspiration for this.

+4
source

You can try

 Y[X==X.max(axis=0)].reshape(X.max(axis=0).shape) 
+2
source

All Articles