Home > Mobile >  How to arrange a numpy list in order according to the order of a list or string
How to arrange a numpy list in order according to the order of a list or string

Time:11-12

i have a numpy array:

import numpy as np
phrase = np.array(list("eholl")) 
a = 'hello'

i would like to sort the variable, according to the order of letters (h first, e second...) inside the variable "a" that result into the array ordered:

Tried:

z = np.sort(phrase, order=a)

print(z)

Output that i want:

hello

Error:

ValueError                                Traceback (most recent call last)
<ipython-input-10-64807c091753> in <module>
      2 phrase = np.array(list("eholl"))
      3 a = 'hello'
----> 4 z = np.sort(phrase, order=a)
      5 
      6 print(z)

<__array_function__ internals> in sort(*args, **kwargs)

/usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in sort(a, axis, kind, order)
    996     else:
    997         a = asanyarray(a).copy(order="K")
--> 998     a.sort(axis=axis, kind=kind, order=order)
    999     return a
   1000 

**ValueError: Cannot specify order when the array has no fields.**

CodePudding user response:

order argument of np.sort is to specify which fields to compare first, second, etc. It doesn't help you.

If you don't require the immediate output of the sorting function is a numpy array, you can simply use built-in function sorted. You can specify a key function via its key argument. In your case, the sorting keys are the indices in a string, which can be obtained via str.find.

import numpy as np
phrase = np.array(list("eholl"))
refer_phrase = 'hello'

# sort by the first position of x in refer_phrase
sorted_phrase_lst = sorted(phrase, key=lambda x: refer_phrase.find(x))
print(sorted_phrase_lst)
# ['h', 'e', 'l', 'l', 'o']
sorted_phrase_str = ''.join(sorted_phrase_lst)
print(sorted_phrase_str)
# hello
  • Related