I have a numpy array:
JavaScript
x
2
1
[5,6,7,6,1,9,10,3,1,6]
2
I want the same unique array back, but sorted descending in the order of occurrences of the elements. In this example, 6 occurs 3 times, 1 occurs 2 times and all the other elements only occur 1 time, so the result should be:
JavaScript
1
2
1
[6,1,5,10,9,7,3]
2
Does anyone know how this can be done?
Thanks in advance!
Advertisement
Answer
With pure numpy, you can use numpy.unique
with return_counts=True
, then numpy.argsort
:
JavaScript
1
4
1
a = np.array([5,6,7,6,1,9,10,3,1,6])
2
b, c = np.unique(a, return_counts=True)
3
out = b[np.argsort(-c)]
4
output: array([ 6, 1, 3, 5, 7, 9, 10])