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 can I assign strings to different elements in an array, sort the array, then display the strings based on the sort in Python/Numpy?

I have an array P = np.array([2,3,1]) and I want to assign three strings to each element respectively.
So,:

"str1", "str2", "str3" = P

and after sorting the array:

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

In[]: P = -np.sort(-P)
Out[]: [3,2,1]

I want to then be able to display the strings based on this sort, as:

Out[]: "str2","str1","str3",

Tried assigning variable names to the elements but it won’t display on output as intended.
Tried defining an array of objects with the strings as elements but have trouble assigning them to the numerical values of P.

>Solution :

You can use numpy.argsort.

import numpy as np
P = np.array([2,3,1])
S = np.array(["str1", "str2", "str3"])

sort_idx = np.argsort(-P)
print(S[sort_idx])
# ['str2' 'str1' 'str3']
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