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

如何用Pandas对时间序列重采样,同时获取每日均值与最大值?

Pandas单步重采样同时计算均值与最大值

示例数据

首先构造题目中的时间序列DataFrame:

import pandas as pd

data = {
    'price': [56,70,92,94,81,70,56,68,59,86],
    'vol': [1544,1680,1853,1039,1180,1443,1621,1093,1684,1591]
}
index = pd.to_datetime([
    '2017-01-01 08:00:00',
    '2017-01-01 11:00:00',
    '2017-01-01 14:00:00',
    '2017-01-02 08:00:00',
    '2017-01-02 11:00:00',
    '2017-01-02 14:00:00',
    '2017-01-03 08:00:00',
    '2017-01-03 11:00:00',
    '2017-01-03 14:00:00',
    '2017-01-04 08:00:00'
])
df = pd.DataFrame(data, index=index)

问题描述

已知通过df = df.resample('1d').mean()可获取每日均值,df = df.resample('1d').max()可获取每日最大值,但能否通过单步操作完成重采样,直接得到包含日期索引、price_mean、vol_mean、price_max、vol_max的每日数据?

解决方案

可以利用resample结合agg()方法,为每个列指定需要计算的聚合函数并直接重命名输出列,实现单步完成需求:

# 单步重采样,同时计算均值和最大值并自定义列名
result = df.resample('1d').agg(
    price_mean=('price', 'mean'),
    vol_mean=('vol', 'mean'),
    price_max=('price', 'max'),
    vol_max=('vol', 'max')
).round(2)  # 可选:保留两位小数优化输出格式

print(result)

输出结果

price_mean  vol_mean  price_max  vol_max
2017-01-01       72.67    1692.33         92     1853
2017-01-02       81.67    1220.67         94     1443
2017-01-03       61.00    1466.00         68     1684
2017-01-04       86.00    1591.00         86     1591

补充说明

  • 该方法基于Pandas 0.25+版本支持的关键字参数式聚合,用新列名=(原列名, 聚合函数)的格式,直接定义输出列的含义和计算逻辑
  • 聚合函数既可以用字符串别名(如'mean'、'max'),也可以传入Pandas内置函数(如pd.Series.mean)
  • 如果需要快速对所有列计算多个聚合函数,也可以用df.resample('1d').agg(['mean', 'max']),但输出会是多层列索引,可通过result.columns = [f'{col}_{stat}' for col, stat in result.columns]转为单层索引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:26:20