Home > Net >  How can I assign strings to different elements in an array, sort the array, then display the strings
How can I assign strings to different elements in an array, sort the array, then display the strings

Time:01-06

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.

CodePudding user response:

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']
  • Related