Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find maximums' indexes by row with Numpy?

I have np 2d array and want to get indexes of max by row.

For example:

3 2 1 3 1
0 4 4 1 2
1 0 1 1 2

Maximum by row is
[3, 4, 2].
Indexes are
[(0,0) (0,3) (1,1) (1,2) (2,4)]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried smth like this

buf = np.apply_along_axis(lambda x: zip(np.where(x == np.max(x))), axis=1, arr=B)

or this

buf = np.where(B == np.max(B,axis = 1))

But it doesnt work.

Also I can’t use loops (otherwise I wouldn’t use numpy either)

>Solution :

After finding max you need set each max as one row then searching in base array like below:

>>> a = np.array([[3 ,2 ,1 ,3 ,1],[0, 4 ,4 ,1 ,2],[1, 0, 1, 1, 2]])

>>> np.max(a, axis=1)
array([3, 4, 2])

>>> np.max(a, axis=1)[:,None]
array([[3],
       [4],
       [2]])

>>> np.argwhere(a==np.max(a,1)[:,None])
array([[0, 0],
       [0, 3],
       [1, 1],
       [1, 2],
       [2, 4]])

If you want output like as tuple in your question you can try this:

>>> list(map(tuple, np.argwhere(a==np.max(a,1)[:,None])))
[(0, 0), (0, 3), (1, 1), (1, 2), (2, 4)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading