【问题标题】:How to find median in Numpy 2d array with matching column如何在具有匹配列的 Numpy 2d 数组中找到中位数
【发布时间】:2022-02-24 02:51:54
【问题描述】:

根据我的基本数学,我知道列出的所有工作的平均工资是 40000,但我如何使用 NumPy 获得呢?

例如找出所有列出的工作的中位数的薪水

  • 第一列 = 薪水

  • 第二列 = 没有。招聘广告

     ``` x = np.array([
               [10000, 329],
               [20000, 329],
               [30000, 323],
               [40000, 310],
               [50000, 284],
               [60000, 232],
               [70000, 189],
               [80000, 130],
               [90000, 87],
               [100000, 71]]
               )
    

【问题讨论】:

  • 您正在寻找加权中位数,其中第二列是权重。这不是 numpy 内置的,但您可以编写一个如 herehere 演示的函数。第二个链接是更通用的分位数解决方案(中位数为 0.50 分位数)。

标签: numpy


【解决方案1】:

您有一个频率表。您有兴趣从x[:, 0] 中找到与中点落在累积频率上的位置相对应的第一个值。

你可以使用:

def median_freq_table(freq_table: np.ndarray) -> float:
    """
    Find median of an array represented as a frequency table [[ val, freq ]].
    """
    values = freq_table[:, 0]
    freqs = freq_table[:, 1]

    # cumulative frequencies
    cf = np.cumsum(freqs)
    # total number of elements
    n = cf[-1]

    # get the left and right buckets
    # of where the midpoint falls,
    # accounting for both evend and odd lengths
    l = (n // 2 - 1) < cf
    r = (n // 2) < cf

    # median is the midpoint value (which falls in the same bucket)
    if n % 2 == 1 or (l == r).all():
        return values[r][0]
    # median is the mean between the mid adjacent buckets
    else:
        return np.mean(values[l | r][:2])

您的意见:

>>> xs = np.array(
    [
        [10000, 329],
        [20000, 329],
        [30000, 323],
        [40000, 310],
        [50000, 284],
        [60000, 232],
        [70000, 189],
        [80000, 130],
        [90000, 87],
        [100000, 71],
    ]
)
>>> median_freq_table(xs)
40000

简单的偶数数组:

>>> xs = np.array([[1, 3], [10, 3]])
>>> median_freq_table(xs)
5.5

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2016-04-28
    • 2013-08-28
    • 2014-10-29
    相关资源
    最近更新 更多