Find the maximum of each row in a numpy array and the corresponding element in another array of the same size

I am new to Python and still cannot call myself a Python programmer. Speaking of which, please bear with me if my question makes no sense.

Question:

I have two numpy arrays of the same size, for example. A and B, where A.shape is equal to B.shape, and both are equal (5,1000), and I want to find the maximum value of each row in and the corresponding element of the element in B. For example, if in the fourth row from A, the index is maximum element is 104, then I would like to find the 104th element of the fourth row in array B and the same for the rest of the rows.

I know I can do this by going line by line, but I was wondering if there is a more elegant way to do this. For example, if I did this in MATLAB, I would write the following code:

B(bsxfun(@eq,A,max(A,[],2))) 

Any help that would help me in the right direction would be greatly appreciated.

+6
source share
3 answers

Here's a numpy idiom for doing the numpy same thing:

 b[np.arange(len(a)), np.argmax(a, axis=1)] 

For instance:

 >>> a = np.array([ [1, 2, 0], [2, 1, 0], [0, 1, 2] ]) >>> b = np.array([ [1, 2, 3], [1, 2, 3], [1, 2, 3] ]) >>> b[np.arange(len(a)), np.argmax(a, axis=1)] array([2, 1, 3]) 
+6
source

As a bsxfun lover, it's great to see people trying to reproduce the same functionality in other programming languages. Now bsxfun is basically a broadcasting mechanism that also exists in NumPy. In NumPy, this is achieved by creating Singleton sizes with np.newaxis or just None .

Returning to the question in context, a solution based on broadcasting equivalent can be implemented, as shown in the example run -

 In [128]: A Out[128]: array([[40, 63, 67, 65, 19], [85, 55, 66, 92, 88], [50, 1, 23, 6, 59], [67, 55, 46, 78, 3]]) In [129]: B Out[129]: array([[78, 63, 45, 34, 81], [ 5, 38, 28, 61, 66], [ 3, 65, 16, 25, 32], [72, 1, 31, 75, 6]]) In [130]: B[A == A.max(axis=1)[:,None]] Out[130]: array([45, 61, 32, 75]) 
+1
source

print np.max(A[i]) This will give the highest result in the i th row of the numpy matrix.

0
source

All Articles