【问题标题】:Max frequency 1d array in a 2d numpy array2d numpy 数组中的最大频率 1d 数组
【发布时间】:2019-02-27 16:02:59
【问题描述】:

我有一个 2d numpy 数组:

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

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

【问题讨论】:

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


    【解决方案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)
    • @DanielF 真的!感谢您提醒该功能!或者我们可以简单地使用np.dot。编辑了那部分。
    • 另外,您的第二个解决方案仅适用于小于或等于 3 的 a.shape[-1]。如果您使用 256 ** np.arange(8, dtype = 'int64'),则为 7。否则你会溢出。
    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多