Home > Net >  numpy array --> sort descending unique values base count of values
numpy array --> sort descending unique values base count of values

Time:06-08

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!

CodePudding user response:

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

CodePudding user response:

You can use collections.Counter and most_common() and only return numbers like below:

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)

Output:

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

Explanation:

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