【问题标题】:Can I break values into buckets?我可以将值分成桶吗?
【发布时间】:2019-12-20 07:15:47
【问题描述】:

我有一个包含名称和购买价值的两列数据框。有什么方法可以将它们聚集在 25% 的桶中,以显示它们在总价值中的占比。

因此,前 25% 的销售额占总收入的 50%

我已经按值从小到大进行了分组和排序

df = df.sort_values(['purchase_value'], ascending=[True])

我想要一个表格输出显示:

集团总收入百分比

前 25% - 56%

第二个 25% - 25%

降低 25% - 15%

底部 25% - 4%

【问题讨论】:

    标签: python-3.x dataframe math statistics


    【解决方案1】:

    numpy 提供了一些方便的统计功能,您可以使用这些功能来实现您所需要的。特别是numpy.percentilenumpy.histogram

    import numpy as np
    
    # 100 random numbers for testing purposes
    values = np.random.rand(100)
    # values = np.array(df.purchase_value)
    
    # Get the values on the boundary of each percentile
    q_list = [0, 25, 50, 75, 100]
    percentiles = list(np.percentile(values, q_list))
    
    # Sum the values in the bin between each pair of percentiles
    bin_sums = np.histogram(values, bins=percentiles, weights=values)[0]
    
    # Normalize by the total amount of value
    bin_percents = 100 * bin_sums / np.sum(bin_sums)
    
    # Output
    for left, right, percent in zip(q_list[:-1], q_list[1:], bin_percents):
        print("Portion of value between {}% and {}%: {}%".format(left, right, percent))
    
    # Portion of value between 0% and 25%: 6.7259763107428965%
    # Portion of value between 25% and 50%: 17.0792197951553%
    # Portion of value between 50% and 75%: 31.52807116533235%
    # Portion of value between 75% and 100%: 44.66673272876946%
    

    【讨论】:

    • 非常感谢您的回答,我收到一个奇怪的错误,说 100% 的收入落在前 75-100% 中
    • @Cheese-Lord 你能提供一些发生这种情况的示例值吗?
    • @Cheese-Lord 从您想要的输出开始并向后工作:(1)您如何计算 56% 的值来自前 25% 的值?将前 25% 的值相加,然后除以总值。 (2) 如何找到前 25% 的值?它们应该大于第 25% 的最大值(第 25 个百分位数)。 (3) 如何在python中找到第25%的最大值? numpy.percentile
    猜你喜欢
    • 2019-02-22
    • 2012-09-25
    • 2018-06-04
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    相关资源
    最近更新 更多