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

官方文档

例子数据

相关推荐
老胖闲聊1 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点1 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI1 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python
weixin_505154462 小时前
数字孪生在建设智慧城市中可以起到哪些作用或帮助?
大数据·人工智能·智慧城市·数字孪生·数据可视化
行云流水剑3 小时前
【学习记录】如何使用 Python 提取 PDF 文件中的内容
python·学习·pdf
心扬3 小时前
python生成器
开发语言·python
mouseliu3 小时前
python之二:docker部署项目
前端·python
狂小虎4 小时前
亲测解决self.transform is not exist
python·深度学习
Python智慧行囊4 小时前
Python 中 Django 中间件:原理、方法与实战应用
python·中间件·架构·django·开发