Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Maximum of 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]]]

At first I want the maximum along axis zero with X.max(axis = 0)):

which gives me:

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

The next step is now my problem; I would like to call the location of each 10 and create a new 2D array from another 3D array which has the same dimeonsions as X.

for example teh array with same dimensions looks like that:

 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 location of the maximum in X and create a 2D array from the numbers and location in Y.

the answer in this case should then be:

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

Thank you for your help in advance :)

like image 937
BastHut Avatar asked Jun 23 '15 12:06

BastHut


People also ask

How do you find the maximum value of a NP array?

amax() , or . max() to find maximum values for an array along various axes. You've also used np. nanmax() to find the maximum values while ignoring nan values, as well as np.

What does argmax do in NumPy?

Returns the indices of the maximum values along an axis. Input array. By default, the index is into the flattened array, otherwise along the specified axis.

What is Max NumPy in Python?

maximum() function is used to find the element-wise maximum of array elements. It compares two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned.

Which of the following functions helps find the maximum value number in the NumPy?

Here, we'll calculate the maximum value of our NumPy array by using the np. max() function.


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 provided the inspiration for this

like image 68
tmdavison Avatar answered Nov 15 '22 11:11

tmdavison


You could try

Y[X==X.max(axis=0)].reshape(X.max(axis=0).shape)
like image 23
Noel Segura Meraz Avatar answered Nov 15 '22 12:11

Noel Segura Meraz