Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the second most common number in an array?

Tags:

python

scipy

I have tried using scipy.stats mode to find the most common value. My matrix contains a lot of zeros, though, and so this is always the mode.

For example, if my matrix looks like the following:

array = np.array([[0, 0, 3, 2, 0, 0],
             [5, 2, 1, 2, 6, 7],
             [0, 0, 2, 4, 0, 0]])

I'd like to have the value of 2 returned.

like image 244
user12800 Avatar asked Oct 28 '25 12:10

user12800


1 Answers

Try collections.Counter:

import numpy as np
from collections import Counter

a = np.array(
  [[0, 0, 3, 2, 0, 0],
   [5, 2, 1, 2, 6, 7],
   [0, 0, 2, 4, 0, 0]]
)

ctr = Counter(a.ravel())
second_most_common_value, its_frequency = ctr.most_common(2)[1]
like image 140
Lynn Avatar answered Oct 31 '25 01:10

Lynn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!