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

官方文档

例子数据

相关推荐
山土成旧客3 分钟前
【Python学习打卡-Day35】从黑盒到“玻璃盒”:掌握PyTorch模型可视化、进度条与推理
pytorch·python·学习
@zulnger4 分钟前
python 学习笔记(循环)
笔记·python·学习
No_Merman11 分钟前
【DAY28】元组和os模块
python
iuu_star25 分钟前
金融数据-基于Streamlit的金融数据分析平台开发详解
python·金融·数据挖掘
智航GIS29 分钟前
9.3 Excel 自动化
python·自动化·excel
草莓熊Lotso30 分钟前
Python 库使用全攻略:从标准库到第三方库(附实战案例)
运维·服务器·汇编·人工智能·经验分享·git·python
我送炭你添花33 分钟前
Pelco KBD300A 模拟器:06+6.键盘按键扩展、LCD 优化与指示灯集成(二次迭代)
python·自动化·计算机外设·运维开发
vibag34 分钟前
RAG项目实践
python·语言模型·langchain·大模型
猫头虎37 分钟前
如何解决pip报错 import pandas as pd ModuleNotFoundError: No module named ‘pandas‘问题
java·python·scrapy·beautifulsoup·pandas·pip·scipy
飞天小蜈蚣39 分钟前
python-django_ORM的基本操作
android·python·django