在一个二维的numpy数组中,最高频率的一维数组是什么?

3

I've a 2d numpy array:

array([[21, 17, 11],
   [230, 231, 232],
   [21, 17, 11]], dtype=uint8)

我希望找到出现频率最高的1维数组。对于上述2维数组而言,它是 [21, 17, 11]。这有点像统计学中的 mode。

1个回答

1
我们可以使用 np.unique 函数并带上可选参数 return_counts 来获取每个唯一行的计数,最后使用 argmax() 来选择计数最大的行。
# a is input array
unq, count = np.unique(a, axis=0, return_counts=True)
out = unq[count.argmax()]

对于uint8类型的数据,我们也可以将每行降为一个标量,然后使用np.unique将其转换为1D
s = 256**np.arange(a.shape[-1])
_, idx, count = np.unique(a.dot(s), return_index=True, return_counts=True)
out = a[idx[count.argmax()]]

如果我们正在处理具有3D(最后一个轴是颜色通道)的彩色图像,并且想要获取最显著的颜色,则需要使用a.reshape(-1,a.shape[-1])进行重塑,然后将其提供给所提出的方法。

“np.tensordot(a, s, axes = ((-1), (0)))”不就是“np.tensordot(a, s, 1)”吗? - Daniel F
@DanielF 确实!感谢您提醒我们该功能!或者我们可以直接使用 np.dot。已编辑该部分。 - Divakar
2
你的第二个解决方案仅适用于 a.shape[-1] 小于或等于3。如果你使用 256 ** np.arange(8, dtype = 'int64'),则最大为7。否则会溢出。 - Daniel F

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接