Skip to content
Advertisement

numpy array –> sort descending unique values base count of values

I have a numpy array:

[5,6,7,6,1,9,10,3,1,6]

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:

[6,1,5,10,9,7,3]

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:

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)]

output: array([ 6, 1, 3, 5, 7, 9, 10])

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement