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

官方文档

例子数据

相关推荐
wow_DG2 分钟前
【Python✨】VS Code 秒开 Python 类型检查:一招 mypy + settings.json 让你的 Bug 原地现形!
python·json·bug
Aspect of twilight19 分钟前
LeetCode华为大模型岗刷题
python·leetcode·华为·力扣·算法题
空影星36 分钟前
高效追踪电脑使用时间,Tockler助你优化时间管理
python·django·flask
LiLiYuan.1 小时前
【Lombok库常用注解】
java·开发语言·python
不去幼儿园1 小时前
【启发式算法】灰狼优化算法(Grey Wolf Optimizer, GWO)详细介绍(Python)
人工智能·python·算法·机器学习·启发式算法
二川bro1 小时前
数据可视化进阶:Python动态图表制作实战
开发语言·python·信息可视化
青青子衿_212 小时前
TikTok爬取——视频、元数据、一级评论
爬虫·python·selenium
忘却的旋律dw2 小时前
使用LLM模型的tokenizer报错AttributeError: ‘dict‘ object has no attribute ‘model_type‘
人工智能·pytorch·python
学术小白人2 小时前
会议第一轮投稿!2026年物联网、数据科学与先进计算国际学术会议(IDSAC2026)
人工智能·物联网·数据分析·能源·制造·教育·rdlink研发家
20岁30年经验的码农2 小时前
Java RabbitMQ 实战指南
java·开发语言·python