我有一個 numpy 陣列:
import numpy as np
phrase = np.array(list("eholl"))
a = 'hello'
我想根據變數“a”中的字母順序(h first,e second ...)對變數進行排序,結果排列成有序陣列:
試過:
z = np.sort(phrase, order=a)
print(z)
我想要的輸出:
hello
錯誤:
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.**
uj5u.com熱心網友回復:
order的引數np.sort是指定首先比較哪些欄位,第二個等。它對您沒有幫助。
如果你不需要排序函式的立即輸出是一個 numpy 陣列,你可以簡單地使用內置函式sorted。您可以通過其引數指定鍵功能。key在您的情況下,排序鍵是字串中的索引,可以通過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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532454.html
上一篇:按列值對單行資料框進行排序
