Power Query按列分组计算百分位,如何实现无自定义函数单步方案?
Power Query 分组计算百分位实现方案
可应用于按部门统计工时百分位、按区域统计销售额百分位等场景,相同逻辑也可用于其他自定义分组聚合场景。
方法1:自定义函数实现(与Excel PERCENTILE.INC完全对齐)
自定义函数代码
//PercentileInclusive Function (inputSeries as list, percentile as number) => let SeriesCount = List.Count(inputSeries), PercentileRank = percentile * (SeriesCount - 1) + 1, //percentile value between 0 and 1 PercentileRankRoundedUp = Number.RoundUp(PercentileRank), PercentileRankRoundedDown = Number.RoundDown(PercentileRank), Percentile1 = List.Max(List.MinN(inputSeries, PercentileRankRoundedDown)), Percentile2 = List.Max(List.MinN(inputSeries, PercentileRankRoundedUp)), PercentileInclusive = Percentile1 + (Percentile2 - Percentile1) * (PercentileRank - PercentileRankRoundedDown) in PercentileInclusive
分组调用代码
= Table.Group( TableName, {"Grouping Column"}, // 替换为实际分组列名 {{"New Column name", each PercentileInclusive([Column to calculate Percentile of], 0.25)}} // 0.25替换为实际需要的百分位数值 )
示例验证
输入数据:
| 笔类型 | 销量 |
|---|---|
| Ball-Point | 6,109 |
| Ball-Point | 3,085 |
| Ball-Point | 1,970 |
| Ball-Point | 8,190 |
| Ball-Point | 6,006 |
| Ball-Point | 2,671 |
| Ball-Point | 6,875 |
| Roller | 778 |
| Roller | 9,329 |
| Roller | 7,781 |
| Roller | 4,182 |
| Roller | 2,016 |
| Roller | 5,785 |
| Roller | 1,411 |
按笔类型分组计算25%包容性百分位的输出:
| 笔类型 | 0.25 包容性百分位 |
|---|---|
| Ball-Point | 2,878 |
| Roller | 1,714 |
以上结果与Excel PERCENTILE.INC函数计算结果完全一致。
方法2:内置函数单步实现(无需自定义函数)
之前写法报错或计算全量数据的核心原因是:误用了全局的全量表,忽略了Table.Group的内置分组上下文。Table.Group聚合时,each后的逻辑默认作用于当前分组对应的子表,不需要额外写筛选条件。
正确实现代码
= Table.Group( #"Previous Step Name", // 替换为上一步查询名 {"Grouping Column"}, // 替换为实际分组列名,示例中为"笔类型" { {"New Column name", each List.Percentile([Column to calculate Percentile of], 0.25, [Mode=PercentileMode.Inc]){0}, type number} } )
参数说明:
[Column to calculate Percentile of]:替换为需要计算百分位的列名,示例中为"销量"0.25:替换为需要的百分位数值,取值范围0到1[Mode=PercentileMode.Inc]:指定为包容性百分位,和Excel PERCENTILE.INC、方法1的计算结果完全一致。如果需要排他百分位可改为PercentileMode.Exc
保留Table.SelectRows写法的修正方案(不推荐,效率较低)
如果是在去重后的分组表中添加自定义列的场景,//Condition//位置的筛选条件需要匹配当前行的分组字段值:
= List.Percentile( Table.Column( Table.SelectRows(#"Previous Step Name", (x) => x[Grouping Column] = [Grouping Column]), "Column to calculate Percentile of" ), 0.25, [Mode=PercentileMode.Inc] ){0}
该方案在数据量较大时性能远低于直接使用Table.Group的内置上下文,仅做原理参考。
内容的提问来源于stack exchange,提问作者plasmas222
相关产品推荐
相关产品推荐

