如何在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
相关产品推荐
相关产品推荐

