2d numpy数组中的最大频率1d数组

时间:2018-09-24 07:15:05

标签: arrays python-3.x python-2.7 numpy mode

我有一个二维的numpy数组:

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

我想找到频率更高的1d数组。对于上面的2d数组,它是: [21、17、11]。类似于统计数据中的模式。

1 个答案:

答案 0 :(得分: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类型的数据,我们还可以通过将每一行缩小为一个标量,然后使用1D-

来转换为np.unique
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])进行整形,然后将其输入提出的方法。

相关问题