如何使用pandas的resample重采样
这篇文章主要讲解了如何使用pandas的resample重采样,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
Pandas中的resample,重新采样,是对原样本重新处理的一个方法,是一个对常规时间序列数据重新采样和频率转换的便捷的方法。
降采样:高频数据到低频数据
升采样:低频数据到高频数据
主要函数:resample()(pandas对象都会有这个方法)
resample方法的参数
首先创建一个Series,采样频率为一分钟。
>>> index = pd.date_range('1/1/2000', periods=9, freq='T')>>> series = pd.Series(range(9), index=index)>>> series2000-01-01 00:00:00 02000-01-01 00:01:00 12000-01-01 00:02:00 22000-01-01 00:03:00 32000-01-01 00:04:00 42000-01-01 00:05:00 52000-01-01 00:06:00 62000-01-01 00:07:00 72000-01-01 00:08:00 8Freq: T, dtype: int64
降低采样频率为三分钟
>>> series.resample('3T').sum()2000-01-01 00:00:00 32000-01-01 00:03:00 122000-01-01 00:06:00 21Freq: 3T, dtype: int64
降低采样频率为三分钟,但是每个标签使用right来代替left。请注意,bucket中值的用作标签。
>>> series.resample('3T', label='right').sum()2000-01-01 00:03:00 32000-01-01 00:06:00 122000-01-01 00:09:00 21Freq: 3T, dtype: int64
降低采样频率为三分钟,但是关闭right区间。
>>> series.resample('3T', label='right', closed='right').sum()2000-01-01 00:00:00 02000-01-01 00:03:00 62000-01-01 00:06:00 152000-01-01 00:09:00 15Freq: 3T, dtype: int64
增加采样频率到30秒
>>> series.resample('30S').asfreq()[0:5] #select first 5 rows2000-01-01 00:00:00 02000-01-01 00:00:30 NaN2000-01-01 00:01:00 12000-01-01 00:01:30 NaN2000-01-01 00:02:00 2Freq: 30S, dtype: float64
增加采样频率到30S,使用pad方法填充nan值。
>>> series.resample('30S').pad()[0:5]2000-01-01 00:00:00 02000-01-01 00:00:30 02000-01-01 00:01:00 12000-01-01 00:01:30 12000-01-01 00:02:00 2Freq: 30S, dtype: int64
增加采样频率到30S,使用bfill方法填充nan值。
>>> series.resample('30S').bfill()[0:5]2000-01-01 00:00:00 02000-01-01 00:00:30 12000-01-01 00:01:00 12000-01-01 00:01:30 22000-01-01 00:02:00 2Freq: 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 82000-01-01 00:03:00 172000-01-01 00:06:00 26Freq: 3T, dtype: int64
看完上述内容,是不是对如何使用pandas的resample重采样有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。