我有一個 numpy 陣列:
[5,6,7,6,1,9,10,3,1,6]
我想要回傳相同的唯一陣列,但按元素出現的順序降序排序。在這個例子中,6 出現了 3 次,1 出現了 2 次,所有其他元素只出現了 1 次,所以結果應該是:
[6,1,5,10,9,7,3]
有誰知道如何做到這一點?
提前致謝!
uj5u.com熱心網友回復:
使用純 numpy,您可以使用numpy.uniquewith return_counts=True,然后numpy.argsort:
a = np.array([5,6,7,6,1,9,10,3,1,6])
b, c = np.unique(a, return_counts=True)
out = b[np.argsort(-c)]
輸出:array([ 6, 1, 3, 5, 7, 9, 10])
uj5u.com熱心網友回復:
您可以使用collections.Counter并且most_common()只回傳如下數字:
from collections import Counter
import numpy as np
arr = np.array([5,6,7,6,1,9,10,3,1,6])
res = [num for (num, cnt) in Counter(arr).most_common()]
print(res)
# If you want to return the res as a numpy array:
res = np.asarray(res)
輸出:
[6, 1, 5, 7, 9, 10, 3]
解釋:
>>> Counter(arr)
Counter({5: 1, 6: 3, 7: 1, 1: 2, 9: 1, 10: 1, 3: 1})
>>> Counter(arr).most_common()
[(6, 3), (1, 2), (5, 1), (7, 1), (9, 1), (10, 1), (3, 1)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/487607.html
上一篇:生成隨機值并將結果附加到下一列
