使用Pandas DataFrame.resample来处理时间序列

Pandas DataFrame.resample方法详解

Pandas库中的DataFrame.resample方法是用于对时间序列数据进行频率转换和重采样的便捷方法。该方法要求对象具有类似日期时间的索引(DatetimeIndex、PeriodIndex或TimedeltaIndex),或者调用者必须将一个类似日期时间的系列/索引的标签传递给关键字参数on/level

参数说明

  • rule:DateOffset、Timedelta或字符串,代表目标转换的偏移量。

  • axis:{0或'index',1或'columns'},默认为0。用于上采样或下采样的轴。对于Series,此参数未使用,默认为0。必须是DatetimeIndex、TimedeltaIndex或PeriodIndex。

  • closed:{'right','left'},默认为None。封闭的区间边界。除了'M'、'A'、'Q'、'BM'、'BA'、'BQ'和'W'的所有频率偏移,默认为'left'。

  • label:{'right','left'},默认为None。用于标记桶的区间边缘标签。除了'M'、'A'、'Q'、'BM'、'BA'、'BQ'和'W'的所有频率偏移,默认为'left'。

  • convention:{'start','end','s','e'},默认为'start'。仅适用于PeriodIndex,控制使用规则的开始或结束。

  • kind:{'timestamp','period'},可选,默认为None。传递'timestamp'将结果索引转换为DateTimeIndex,传递'period'将其转换为PeriodIndex。默认保留输入表示形式。

  • on:字符串,可选。对于DataFrame,用于重采样的列而不是索引。列必须类似于日期时间。

  • level:字符串或整数,可选。对于MultiIndex,用于重采样的级别(名称或编号)。级别必须类似于日期时间。

  • origin:Timestamp或字符串,默认为'start_day'。调整分组的时间戳。原点的时区必须与索引的时区匹配。如果是字符串,必须是以下之一:

    • 'epoch':原点是1970-01-01。
    • 'start':原点是时间序列的第一个值。
    • 'start_day':原点是时间序列的午夜的第一天。
    • 'end':原点是时间序列的最后一个值。
    • 'end_day':原点是最后一天午夜的天花板。

    在1.3.0版本中新增。注意:只对Tick频率(即固定频率,如天、小时和分钟,而不是月份或季度)有效。

  • offset:Timedelta或字符串,默认为None。添加到原点的偏移时间间隔。

  • group_keys :bool,默认为False。是否在对重采样对象使用.apply()时将组键包含在结果索引中。

返回值

pandas.api.typing.Resampler 重采样器对象。

示例

以下是一些示例以及对应的代码:

示例 1:将时间序列数据进行降采样为3分钟间隔,对每个区间内的数值求和。

yaml 复制代码
index = pd.date_range('1/1/2000', periods=9, freq='T')
series = pd.Series(range(9), index=index)

2000-01-01 00:00:00    0
2000-01-01 00:01:00    1
2000-01-01 00:02:00    2
2000-01-01 00:03:00    3
2000-01-01 00:04:00    4
2000-01-01 00:05:00    5
2000-01-01 00:06:00    6
2000-01-01 00:07:00    7
2000-01-01 00:08:00    8
Freq: T, dtype: int64


result = series.resample('3T').sum()
print(result)
2000-01-01 00:00:00     3
2000-01-01 00:03:00    12
2000-01-01 00:06:00    21
Freq: 3T, dtype: int64

示例 2:将时间序列数据进行上采样为30秒间隔,利用ffill和bfill方法填充NaN值。

yaml 复制代码
up_sample_ffill = series.resample('30S').ffill()[0:5]  # 使用ffill方法填充NaN值
print(up_sample_ffill)

2000-01-01 00:00:00    0
2000-01-01 00:00:30    0
2000-01-01 00:01:00    1
2000-01-01 00:01:30    1
2000-01-01 00:02:00    2
Freq: 30S, dtype: int64
py 复制代码
up_sample_bfill = series.resample('30S').bfill()[0:5]  # 使用bfill方法填充NaN值
print(up_sample_bfill)


2000-01-01 00:00:00    0
2000-01-01 00:00:30    1
2000-01-01 00:01:00    1
2000-01-01 00:01:30    2
2000-01-01 00:02:00    2

2例子展示

  • 向下采样为Day
ini 复制代码
xdat = df.resample('D', on='Datetime').sum().reset_index()[['Datetime', 'PJME']].rename(columns={"Datetime": "ds", "PJME": "y"})
xdat['y'] /= 10^9
# we purge the leading zeros, along with the last observation - we only have a few hours of the last day in the sample => incomplete day
ix = np.where(xdat['y'] > 0)[0][0]
xdat = xdat.iloc[ix:-1]
xdat.set_index('ds').plot(xlabel = '')
  • 向下采样为Month
py 复制代码
xdat = df.resample('M', on='Datetime').sum().reset_index()[['Datetime', 'PJME']].rename(columns={"Datetime": "ds", "PJME": "y"})
xdat['y'] /= 10^9
# we purge the leading zeros, along with the last observation - we only have a few hours of the last day in the sample => incomplete day
ix = np.where(xdat['y'] > 0)[0][0]
xdat = xdat.iloc[ix:-1]
xdat.set_index('ds').plot(xlabel = '')

结语

DataFrame.resample是一个功能强大的工具,用于对时间序列数据进行频率转换和重采样。通过适当地使用不同的参数组合,可以灵活地处理各种时间序列数据,并进行相应的处理和分析。

官方文档

例子数据

相关推荐
数据智能老司机2 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机3 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机3 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机3 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i4 小时前
drf初步梳理
python·django
每日AI新事件4 小时前
python的异步函数
python
这里有鱼汤5 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook14 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室14 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三16 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试