如何按频率对 NumPy 数组进行排序?

Arc*_*lah 5 python arrays sorting numpy

我正在尝试按元素频率对 NumPy 数组进行排序。因此,例如,如果有一个数组 [3,4,5,1,2,4,1,1,2,4],输出将是另一个 NumPy,从最常见到最不常见的元素(无重复)排序。所以解决方案是 [4,1,2,3,5]。如果两个元素出现的次数相同,则最先出现的元素将首先放置在输出中。我试过这样做,但我似乎无法得到一个功能性的答案。到目前为止,这是我的代码:

temp1 = problems[j]
indexes = np.unique(temp1, return_index = True)[1]
temp2 = temp1[np.sort(indexes)]
temp3 = np.unique(temp1, return_counts = True)[1]
temp4 = np.argsort(temp3)[::-1] + 1
Run Code Online (Sandbox Code Playgroud)

其中问题 [j] 是一个 NumPy 数组,如 [3,4,5,1,2,4,1,1,2,4]。到目前为止, temp4 返回 [4,1,2,5,3] 但它不正确,因为它无法处理两个元素出现相同次数的情况。

jpp*_*jpp 2

仍然可以使用 NumPy 数组的非 NumPy 解决方案是使用OrderedCounter后跟sorted自定义函数:

from collections import OrderedDict, Counter

class OrderedCounter(Counter, OrderedDict):
    pass

L = [3,4,5,1,2,4,1,1,2,4]

c = OrderedCounter(L)
keys = list(c)

res = sorted(c, key=lambda x: (-c[x], keys.index(x)))

print(res)

[4, 1, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)