【问题标题】:Count number of elements in a specific bin计算特定 bin 中的元素数
【发布时间】:2019-04-02 19:19:01
【问题描述】:

我很好奇是否可以计算直方图中特定 bin 的元素数量,即 0-10 范围内的所有元素

你会怎么做?

例如plt.hist(数据, bins=[0, 10, 20, 30, 40, 50, 100]) 是否可以计算数据集中进入 bin 0-10 的所有元素

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    Matplotlib 直方图返回每个 bin 的计数:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.random.uniform(0, 100, 1000)
    
    counts, edges, plot = plt.hist(x, bins=[0, 10, 20, 50, 100])
    print(counts)
    print(counts[0]) # first bin
    

    【讨论】:

    • 所以问题的期望输出是print(counts[0])
    【解决方案2】:

    是的,pd.Series.value_countsbins 参数。

    import pandas as pd
    s = pd.Series(np.random.randint(0,100,50))
    s.value_counts(bins=[0,10,20,30,40,50,60,70,80,90,100]).sort_index()
    

    输出:

    (-0.001, 10.0]    8
    (10.0, 20.0]      6
    (20.0, 30.0]      5
    (30.0, 40.0]      6
    (40.0, 50.0]      2
    (50.0, 60.0]      3
    (60.0, 70.0]      4
    (70.0, 80.0]      3
    (80.0, 90.0]      6
    (90.0, 100.0]     7
    dtype: int64
    

    【讨论】:

    • 投反对票,无需导入pandas。这很简单。只需在最后一个 bin 上正确设置边界即可。
    • 很公平。谢谢@MFisherKDX,如果我再得到两个同意你的反对票,我会删除。
    • @ScottBoston 我实际上是通过谷歌搜索来到这里的,很高兴有一个 pandas 答案(我不使用 matplotlib,但使用 pandas :))。所以是的,OP 的需求可以通过他们使用的原始库来满足,但是关于 SO 的问题也面向公众:D
    猜你喜欢
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2022-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多