You need to enable JavaScript to run this app. 如何在Pandas重采样时使用百分位函数替代max过滤月度数据峰值
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas重采样时使用百分位函数替代max过滤月度数据峰值

实现方案

pandas的resample对象完全支持自定义函数聚合,通过以下几种方式都可以实现按月计算指定百分位的需求:

方法1:使用pandas内置quantile方法(推荐,性能最优)

直接调用resample对象的quantile方法,参数传入需要的百分位数值(如0.99对应99百分位)即可:

# 仅对y字段聚合
df = df.resample('M', on='ds')['y'].quantile(0.99).reset_index()

# 如果需要对所有数值字段做聚合
df = df.resample('M', on='ds').quantile(0.99).reset_index()

方法2:结合numpy的percentile自定义计算

如果需要使用numpy的percentile函数实现,通过agg方法传入自定义函数即可:

import numpy as np

# 单字段聚合
df = df.resample('M', on='ds').agg(
    y=('y', lambda x: np.percentile(x, q=99))
).reset_index()

# 多字段指定不同聚合规则示例
df = df.resample('M', on='ds').agg(
    y_99=('y', lambda x: np.percentile(x, 99)),
    value_mean=('value', 'mean')
).reset_index()

注意:如果数据中存在缺失值,默认会自动跳过计算,如果需要保留缺失值可以添加skipna=False参数


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 04:09:04