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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With