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

官方文档

例子数据

相关推荐
happylifetree1 小时前
Python18(补充):练习
python
weixin_416667962 小时前
银河麒麟V10看门狗试验-1
网络·chrome·python
龙亘川2 小时前
数字化赋能基层协同治理:亘川智城一网统管平台落地实践思考
大数据·人工智能·智慧城市·开源软件·数据可视化
古城小栈2 小时前
Pydantic 从入门到实践全讲解
python
happylifetree2 小时前
Python18:核心语法-数据存储与运算-运算符-算术运算符
python
打工仔折腾 AI2 小时前
从Attention到BERT:双向预训练语言模型到底解决了什么问题
人工智能·后端·python·深度学习·语言模型·bert
迅猛龙办公室3 小时前
实现第一个python程序(HelloWorld)
开发语言·python
躺柒3 小时前
读数据架构知识体系指南12数据导入方法
数据分析·etl·数据架构·elt·数据设计·反向etl
拉格朗日(Lagrange)3 小时前
【第2 章】WorkBuddy 从入门到高手
开发语言·python
老歌老听老掉牙4 小时前
斜抛运动问题分析:给定最大高度与墙面位置的轨迹与时间求解
python·斜抛运动