【问题标题】:How to find the most frequent value in a column using np.histogram()如何使用 np.histogram() 在列中查找最频繁的值
【发布时间】:2020-02-12 11:01:18
【问题描述】:

我有一个 DataFrame,其中一列包含不同的数值。 我想专门使用 np.histogram() 函数找到最常出现的值。

我知道可以使用 column.value_counts().nlargest(1) 等函数来完成此任务,但是,我对如何使用 np.histogram() 函数来实现此目标很感兴趣。

通过这项任务,我希望能够更好地理解函数和结果值,因为文档 (https://numpy.org/doc/1.18/reference/generated/numpy.histogram.html) 中的描述对我来说不是很清楚。

下面我将分享一个用于此任务的值系列示例:

data = pd.Series(np.random.randint(1,10,size=100))

【问题讨论】:

    标签: python pandas numpy histogram


    【解决方案1】:

    这是一种方法:

    import numpy as np
    import pandas as pd
    
    # Make data
    np.random.seed(0)
    data = pd.Series(np.random.randint(1, 10, size=100))
    # Make bins
    bins = np.arange(data.min(), data.max() + 2)
    # Compute histogram
    h, _ = np.histogram(data, bins)
    # Find most frequent value
    mode = bins[h.argmax()]
    # Mode computed with Pandas
    mode_pd = data.value_counts().nlargest(1).index[0]
    # Check result
    print(mode == mode_pd)
    # True
    

    您还可以将bins 定义为:

    bins = np.unique(data)
    bins = np.append(bins, bins[-1] + 1)
    

    或者如果您的数据只包含正数,您可以直接使用np.bincount

    mode = np.bincount(data).argmax()
    

    当然还有scipy.stats.mode

    import scipy.stats
    mode = scipy.stats.mode(data)[0][0]
    

    【讨论】:

    • 嘿,谢谢。那么,您将如何定义为具有 n 个唯一值的集合创建分箱?我看到您在 data.max 中添加了 +2 - 这适用于任意数量的垃圾箱吗?
    • @Maciej 在第一个示例中,我假设data 是整数,现在np.arange(data.min(), data.max() + 1) 将是data 中的值范围,但您需要一个额外的值作为最后一个的上限bin,因此np.arange(data.min(), data.max() + 2)。使用np.unique时,已经得到了排序后的值数组,所以只需要在上限再加一个,我加了最大值加一,bit可以是任意值,只要大于data 中的最大值。逻辑相同,与data 中不同值的数量无关。
    • @Maciej 当然,另一种选择是将 bin 边缘放在小数位,as mathfux suggests
    • 再问一个问题。我知道 hist 保存每个 bin 的计数,或每个 bin 的大小。 Bin_edges 保存垃圾箱。我如何从 np.argmax(hist) 获得感兴趣的值,如果它包含计数,而不是值?
    • @Maciej 你说得对,hist 包含 data 中每个 bin 中的值的数量。所以,如果第一个 bin 是[1, 2),并且data 中有三个1,那么hist[0] 将是3。现在,argmax 为您提供hist 中最大值的索引,因此与该位置对应的 bin 将告诉您最频繁的值。例如,在前面的例子中,如果argmax0,那么对应的bin就是[1, 2),那么最常见的值就是1
    【解决方案2】:

    可以这样做:

    hist, bin_edges = np.histogram(data, bins=np.arange(0.5,10.5))
    result = np.argmax(hist)
    

    您只需要更仔细地阅读文档。它说如果bins[1, 2, 3, 4],那么第一个bin 是[1, 2),第二个是[2, 3),第三个是[3, 4)

    我们会在您的问题中计算 [0.5, 1.5)[1.5, 2.5)、...、[8.5, 9.5) 中的数字数量,并选择最大值的索引。

    以防万一,值得使用

    np.unique(data)[np.argmax(hist)]
    

    如果我们不确定您的排序数据集 np.unique(data) 是否包含所有连续整数 0、1、2、3、...

    【讨论】:

    • 要正确,您必须使用bins=np.arange(-0.5, 10.5),因此第一个bin对应于0,否则argmax返回的值将移动一个(或您可以在结果中添加一个)。关于np.unique,我不确定是否正确,如果data[1, 2, 5, 5, 1, 5] 那么argmax 将给出4np.unique 将返回[1, 2, 5],它会给出错误。
    猜你喜欢
    • 2021-12-09
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多