You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas:带多列分组数据的分位数计算问题

基于Quantity加权计算Age的分组分位数

实现思路

要按Product分组,以Quantity为权重计算Age的指定分位数,需自定义加权分位数函数,结合Pandas分组操作完成计算——核心是按Quantity的累积占比来定位对应Age,而非普通的行数占比。

自定义加权分位数函数

import pandas as pd
import numpy as np

def weighted_percentile(ages, weights, percentile):
    # 按Age排序,同步对应权重排序
    sorted_indices = np.argsort(ages)
    sorted_ages = ages.iloc[sorted_indices]
    sorted_weights = weights.iloc[sorted_indices]
    
    # 计算累积权重及目标权重阈值
    cumulative_weights = np.cumsum(sorted_weights)
    total_weight = cumulative_weights.iloc[-1]
    target_weight = total_weight * percentile
    
    # 找到第一个累积权重达标对应的Age
    for age, cum_weight in zip(sorted_ages, cumulative_weights):
        if cum_weight >= target_weight:
            return age
    return sorted_ages.iloc[-1]

分组计算指定分位数

# 加载原始数据
df = pd.DataFrame({
    'Product': ['Alpha', 'Alpha', 'Alpha', 'Alpha','Alpha', 'Beta', 'Beta', 'Beta','Beta', 'Gamma', 'Gamma', 'Gamma','Delta','Delta','Epsilon','Epsilon','Epsilon','Epsilon'],
    'Age': [0,1,2,5,8,0,2,3,5,1,3,2,8,5,1,5,4,2],
    'Quantity': [114,82,15,35,27,63,32,55,87,50,4,22,6,96,94,3,64,110]
})

# 定义需要计算的分位数
target_percentiles = {
    '70th Percentile (years)': 0.7,
    '90th Percentile (years)': 0.9
}

# 分组执行计算并整理结果
result = df.groupby('Product').apply(
    lambda x: pd.Series(
        {col: weighted_percentile(x['Age'], x['Quantity'], p) for col, p in target_percentiles.items()}
    )
).reset_index()

print(result)

最终输出结果

Product70th Percentile (years)90th Percentile (years)
Alpha02
Beta55
Gamma22
Delta55
Epsilon24

内容的提问来源于stack exchange,提问作者FissionChips

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:42:37