Pandas中的resample,重新采样,是对原样本重新处理的一个方法,是一个对常规时间序列数据重新采样和频率转换的便捷的方法。
降采样高频数据到低频数据
升采样低频数据到高频数据
主要函数resample()(pandas对象都会有这个方法)
resample方法的参数
参数
说明
freq
表示重采样频率,例如‘M'、‘5min',Second(15)
ho='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'
在降采样时,如何设置聚合值的标签,例如,930-935会被标记成930还是935,默认935
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 ros
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
到此这篇关于pandas的resample重采样的使用的文章就介绍到这了,更多相关pandas resample重采样内容请搜索考高分网以前的文章或继续浏览下面的相关文章电脑维修网希望大家以后多多支持考高分网!