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 sort a dict in numpy

I want to write a function func() like this:

import numpy as np

a = np.array([0, 1, 1, 0, 0, 2, 3, 0, 1])
b = np.array([1, 1, 4, 5, 1, 4, 1, 9, 1])

ab = np.array([[0, 1, 1, 0, 0, 2, 3, 0, 1],
               [1, 1, 4, 5, 1, 4, 1, 9, 1]])

grp = np.where(a == 0)[0]  # [0, 3, 4, 7]

def func():
    # return the index of np.max(b[grp]) in a, here it is 7

np.argmax(b[grp]) can only return return the index of np.argmax(b[grp]) in a[grp], here it is 3

I know that dict can do this but numpy seems not supporting dict sorting and spliting like b[grp]

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

Any help is welcome, thanks!

>Solution :

You can use the argmax of filtered b to index the grp

$ grp[np.argmax(b[grp])]

7
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