Tomk07
Tomk07

Reputation: 113

Find the N most frequent numbers in a NumPy array

The accepted answer of the most frequent occurrence is

a = np.array([1,2,3,1,2,1,1,1,3,2,2,1])
counts = np.bincount(a)
print(np.argmax(counts))

But I'm wondering if anybody has an elegant way of finding the top 10 most frequent, for example. Thanks

Upvotes: 0

Views: 127

Answers (2)

Tomk07
Tomk07

Reputation: 113

Here is a very nice answer in the original post that I had missed from Apogentus

values, counts = np.unique(a, return_counts=True)

ind = np.argmax(counts)
print(values[ind])  # prints the most frequent element

ind = np.argpartition(-counts, kth=10)[:10]
print(values[ind])  # prints the 10 most frequent elements

Upvotes: 1

tayler6000
tayler6000

Reputation: 101

Here you are:

for i in range(10):
  largest = np.argmax(counts)
  counts[largest] = 0
  print(largest)

Upvotes: 1

Related Questions