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?

Question:

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:

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.

Asked By: Dordini Balbozhia

||

Answers:

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']
Answered By: I'mahdi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.