pandas的resample重采样

Pandas中的resample,重新采样,是对原样本重新处理的一个方法,是一个对常规时间序列数据重新采样和频率转换的便捷的方法。

降采样:高频数据到低频数据

升采样:低频数据到高频数据

主要函数:resample()(pandas对象都会有这个方法)

resample方法的参数

参数 说明
freq 表示重采样频率,例如‘M’、‘5min’,Second(15)
how=’mean’ 用于产生聚合值的函数名或数组函数,例如‘mean’、‘ohlc’、np.max等,默认是‘mean’,其他常用的值由:‘first’、‘last’、‘median’、‘max’、‘min’
axis=0 默认是纵轴,横轴设置axis=1
fill_method = None 升采样时如何插值,比如‘ffill’、‘bfill’等
closed = ‘right’ 在降采样时,各时间段的哪一段是闭合的,‘right’或‘left’,默认‘right’
label= ‘right’ 在降采样时,如何设置聚合值的标签,例如,9:30-9:35会被标记成9:30还是9:35,默认9:35
loffset = None 面元标签的时间校正值,比如‘-1s’或Second(-1)用于将聚合标签调早1秒
limit=None 在向前或向后填充时,允许填充的最大时期数
kind = None 聚合到时期(‘period’)或时间戳(‘timestamp’),默认聚合到时间序列的索引类型
convention = None 当重采样时期时,将低频率转换到高频率所采用的约定(start或end)。默认‘end’

首先创建一个Series,采样频率为一分钟。

>>> index = pd.date_range('1/1/2000', periods=9, freq='T') >>> series = pd.Series(range(9), index=index) >>> series 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
降低采样频率为三分钟
>>> series.resample('3T').sum() 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
降低采样频率为三分钟,但是每个标签使用right来代替left。请注意,bucket中值的用作标签。
>>> series.resample('3T', label='right').sum() 2000-01-01 00:03:00 3 2000-01-01 00:06:00 12 2000-01-01 00:09:00 21 Freq: 3T, dtype: int64
降低采样频率为三分钟,但是关闭right区间。
>>> series.resample('3T', label='right', closed='right').sum() 2000-01-01 00:00:00 0 2000-01-01 00:03:00 6 2000-01-01 00:06:00 15 2000-01-01 00:09:00 15 Freq: 3T, dtype: int64
增加采样频率到30秒
>>> series.resample('30S').asfreq()[0:5] #select first 5 rows 2000-01-01 00:00:00 0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 1 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2 Freq: 30S, dtype: float64
增加采样频率到30S,使用pad方法填充nan值。
>>> series.resample('30S').pad()[0:5] 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
增加采样频率到30S,使用bfill方法填充nan值。
>>> series.resample('30S').bfill()[0:5] 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 Freq: 30S, dtype: int64
通过apply运行一个自定义函数
>>> def custom_resampler(array_like): ... return np.sum(array_like)+5
>>> series.resample('3T').apply(custom_resampler) 2000-01-01 00:00:00 8 2000-01-01 00:03:00 17 2000-01-01 00:06:00 26 Freq: 3T, dtype: int64
出处:https://blog.csdn.net/wangshuang1631/article/details/52314944

猜你喜欢

转载自www.cnblogs.com/jingsupo/p/pandas-resample.html