我有一个二维的numpy数组:

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


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

最佳答案

我们可以使用np.unique及其可选的arg 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])进行整形,然后将其提供给建议的方法。

关于arrays - 2d numpy数组中的最大频率1d数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52474308/

10-11 22:45
查看更多