首页 > 解决方案 > 一种在范围内查找众数值的方法

问题描述

我在这个结构中有一个 numpy 维度值数组:

arr = array([[3067,   78, 3172,  134],
             [3237,   89, 3394,  128],
             [3475,   87, 3743,  141],
             [3763,   86, 3922,  131],
             [3238,  147, 3259,  154]])

它基本上存储位于屏幕中的数据的位置,其中的值表示为:[x_left, y_top, x_right, y_bottom]]

我只需要处理这些x_left值,因为我试图在页面上找到我最有可能找到这些对象的位置。

我知道scipy.mode,它返回模式值。有没有办法返回多种模式,比如给定 numpy 列中的前 10 个模式值?更好的是,有没有办法使用模式以使模式在给定范围内?例如,上面的行具有和的x_left值,它们非常紧密地对齐。有没有办法将这两个计算为单个模式值?32373238

标签: pythonnumpyscipy

解决方案


您可以将 numpy 数组列转换为 pandas 系列并使用.value_counts()

import pandas as pd
x_left = pd.Series(arr[:,0])
x_left.value_counts()
#3475    1
#3237    1
#3067    1
#3763    1
#3238    1
#dtype: int64

您还可以将值四舍五入到,例如最接近的 10 个整数,以便在范围之间对值进行分组

def customRound(x, base=10):
    return base * round(x/base)
x_left_round = x_left.apply(customRound)
x_left_round.value_counts()
#3240    2
#3760    1
#3070    1
#3480    1
#dtype: int64

然后您可以看到您有两个x_left接近 3240 的值


推荐阅读