如何找到数组中第二常见的数字?

use*_*800 0 python scipy

我尝试使用scipy.stats模式来查找最常见的值。但是,我的矩阵包含很多零,因此这始终是模式。

例如,如果我的矩阵如下所示:

array = np.array([[0, 0, 3, 2, 0, 0],
             [5, 2, 1, 2, 6, 7],
             [0, 0, 2, 4, 0, 0]])
Run Code Online (Sandbox Code Playgroud)

我想得到2退货的价值。

Lyn*_*ynn 6

尝试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]
Run Code Online (Sandbox Code Playgroud)