DataFrame.resample(rule, axis=0, closed=None, label=None, convention='start', kind=None, loffset=None, base=None, on=None, level=None, origin='start_day', offset=None) [source]
重新采样time-series数据。
频率转换和time series重采样的便捷方法。对象必须具有类似datetime
的索引(DatetimeIndex
, PeriodIndex
或TimedeltaIndex
),或将类似datetime
的值传递给on
或level
关键字。
参数: | rule : 表示目标转换的偏移字符串或对象。 axis : 向上采样或向下采样使用哪一个轴。对于级数,默认值为 即沿着行。必须是 或 closed :
除了 所有频率偏移的默认值都是 它们的默认值都是 label : 用哪边标签来标记bucket。 除了 和 所有频率偏移的默认值都是 它们的默认值都是 convention : 默认为 仅对于 kind : 传递 或 保留输入表示形式。 loffset : 调整重新采样的时间标签。 自1.1.0版本以来已弃用 : 应该将 重新取样后的索引。见下文。 base : 对于平均细分1天的频率,聚合间隔的 例如,对于 基数可以从 自1.1.0版本以来已弃用: 您应该使用的新参数是 on : 自1.1.0版本以来已弃用: 应该使用的新参数是 level : 用于重采样的多索引、级别(名称或数字)。 级别必须与日期时间类似。 origin :
调整分组的时间戳。原始时区必须与索引的时区匹配。 如果不使用时间戳,也支持以下值: 1) 2) 2) 新版本1.1.0。 offset : 加到原点的偏移时间。 新版本1.1.0。 |
返回值: | Resampler object |
Notes
有关 更多信息,请参见用户指南。
要了解有关偏移字符串的更多信息,请参见此链接。
例子
1)按月重采样并求平均
import pandas as pd # 创建时间序列数据 rng = pd.date_range('2024-01-01', periods=90, freq='D') df = pd.DataFrame({'value': range(90)}, index=rng) # 按月重采样并求平均 monthly_avg = df.resample('M').mean() print(monthly_avg)
2)非索引列为时间的重采样
import pandas as pd # 创建时间序列数据 rng = pd.date_range('2024-01-01', periods=90, freq='D') df = pd.DataFrame({'value': range(90)}, index=rng) df2 = df.reset_index() df2.columns = ['date', 'value'] # 使用 on 参数指定时间列 monthly_sum = df2.resample('M', on='date').sum() print(monthly_sum)
3)重采样为每 7 天求和
import pandas as pd # 创建时间序列数据 rng = pd.date_range('2024-01-01', periods=90, freq='D') df = pd.DataFrame({'value': range(90)}, index=rng) weekly = df.resample('7D').sum() print(weekly)
4)使用自定义聚合函数(apply)
import pandas as pd import numpy as np # 创建9个一分钟间隔的时间戳索引 index = pd.date_range('1/1/2000', periods=9, freq='T') series = pd.Series(range(9), index=index) print(series) def custom_resampler(x): return np.sum(x) + 5 print(series.resample('3T').apply(custom_resampler))
5)PeriodIndex 按季度转为月度(convention='end')
import pandas as pd import numpy as np q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018Q1', freq='Q', periods=4)) print(q.resample('M', convention='end').asfreq())