Pandas中resample方法详解

来源:互联网 发布:蜂蜜源码 编辑:程序博客网 时间:2024/06/05 02:05

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

方法的格式是:

DataFrame.resample(rulehow=Noneaxis=0fill_method=Noneclosed=Nonelabel=Noneconvention='start',kind

=Noneloffset=Nonelimit=Nonebase=0)

参数详解是:

Parameters:

rule : string

偏移量表示目标字符串或对象转换

axis : int, optional, default 0

closed : {‘right’, ‘left’}

哪一个方向的间隔是关闭的

label : {‘right’, ‘left’}

Which bin edge label to label bucket with

convention : {‘start’, ‘end’, ‘s’, ‘e’}

loffset : timedelta

调整重新取样时间标签

base : int, default 0

频率均匀细分1天,“起源”的聚合的间隔。例如,对于“5分钟”频率,基地可能范围从0到4。默认值为0

首先创建一个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

1 0
原创粉丝点击