Pandas中resample方法详解

Pandas中resample方法详解

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

方便的时间序列的频率转换和重采样方法。对象必须具有类似datetime的索引(DatetimeIndex、PeriodIndex或TimedeltaIndex),或将类似datetime的值传递给on或level关键字。

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)

参数详解是:

参数说明
rule表示目标转换的偏移量字符串或对象
freq表示重采样频率,例如‘M’、‘5min’,Second(15)
how=‘mean’用于产生聚合值的函数名或数组函数,例如‘mean’、‘ohlc’、np.max等,默认是‘mean’,其他常用的值由:‘first’、‘last’、‘median’、‘max’、‘min’
axis=0哪个轴用于向上采样或向下采样。对于序列,这将默认为0,即沿着行。必须是DatetimeIndex, TimedeltaIndex或PeriodIndex。默认是纵轴,横轴设置axis=1
fill_method = None升采样时如何插值,比如‘ffill’、‘bfill’等
closed = ‘right’在降采样时,各时间段的哪一段是闭合的,‘right’或‘left’,默认‘right’
label= ‘right’在降采样时,如何设置聚合值的标签,例如,9:30-9:35会被标记成9:30还是9:35,默认9:35
convention = None当重采样时期时,将低频率转换到高频率所采用的约定(start或end)。默认‘end’
kind = None聚合到时期(‘period’)或时间戳(‘timestamp’),默认聚合到时间序列的索引类型
loffset = None调整重新取样的时间标签
base对于平均细分1天的频率,为累计间隔的“起源”。例如,对于“5min”频率,基数可以从0到4。默认值为0。
on对于数据流,要使用列而不是索引进行重采样。列必须与日期时间类似。
level对于多索引,用于重采样的级别(名称或数字)。级别必须与日期时间相似
origin要调整分组的时间戳。起始时区必须与索引的时区匹配。如果没有使用时间戳,也支持以下值:epoch:原点是1970-01-01’;start ': origin是timeseries的第一个值;“start_day”:起源是timeseries午夜的第一天;
offset加到原点的偏移时间增量
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
'''

将该系列数据采样到3分钟箱中,并对落入箱中的时间戳的值求和。

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
'''

如上所述,将系列下采样到3分钟的容器中,但请使用右侧边缘而不是左侧标记每个容器。 请注意,用作标签的存储桶中的值不包含在其标记的存储桶中。 例如,在原始系列中,存储区2000-01-01 00:03:00包含值3,但重新采样的存储区中标有2000-01-01 00:03:00的总和值不包含3( 如果是,则总和为6,而不是3)。 要包括此值,请关闭bin间隔的右侧,如下面的示例所示。

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
'''

如上所述,将系列降采样到3分钟的箱中,但关闭箱间隔的右侧。

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.0
2000-01-01 00:00:30   NaN
2000-01-01 00:01:00   1.0
2000-01-01 00:01:30   NaN
2000-01-01 00:02:00   2.0
Freq: 30S, dtype: float64

'''

将该系列上采样到30秒的箱子中,并使用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
'''

将序列上采样到30秒的箱子中,并使用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
'''

对于具有PeriodIndex的系列,可以使用关键字约定来控制是使用规则的开始还是结束。
使用“开始”约定按季度重新取样。值被分配到该期间的第一季度。

s = pd.Series([1, 2], index=pd.period_range('2012-01-01',freq='A',periods=2))
s
'''
2012    1
2013    2
Freq: A-DEC, dtype: int64
'''     

s.resample('Q', convention='start').asfreq()
'''
2012Q1    1.0
2012Q2    NaN
2012Q3    NaN
2012Q4    NaN
2013Q1    2.0
2013Q2    NaN
2013Q3    NaN
2013Q4    NaN
Freq: Q-DEC, dtype: float64
'''                                      

使用“结束”惯例按月重新计算季度数。将值赋给该期间的最后一个月。

q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018-01-01',freq='Q',periods=4))
q
'''
2018Q1    1
2018Q2    2
2018Q3    3
2018Q4    4
Freq: Q-DEC, dtype: int64
'''

q.resample('M', convention='end').asfreq()
'''
2018-03    1.0
2018-04    NaN
2018-05    NaN
2018-06    2.0
2018-07    NaN
2018-08    NaN
2018-09    3.0
2018-10    NaN
2018-11    NaN
2018-12    4.0
Freq: M, dtype: float64
'''                                          

对于DataFrame对象,关键字on可用于指定列,而不是用于重新采样的索引。

d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
          'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
df = pd.DataFrame(d)
df['week_starting'] = pd.date_range('01/01/2018',
                                    periods=8,
                                    freq='W')
df
'''
     price  volume week_starting
0     10      50    2018-01-07
1     11      60    2018-01-14
2      9      40    2018-01-21
3     13     100    2018-01-28
4     14      50    2018-02-04
5     18     100    2018-02-11
6     17      40    2018-02-18
7     19      50    2018-02-25
'''
df.resample('M', on='week_starting').mean()
'''
               price  volume
week_starting
2018-01-31     10.75    62.5
2018-02-28     17.00    60.0
'''

对于具有多索引的数据流,关键字级别可用于指定需要在哪个级别进行重采样。

days = pd.date_range('1/1/2000', periods=4, freq='D')
d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
           'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
df2 = pd.DataFrame(d2,
                   index=pd.MultiIndex.from_product([days,
                                                    ['morning',
                                                     'afternoon']]
                                                    ))
df2
'''
                      price  volume
2000-01-01 morning       10      50
           afternoon     11      60
2000-01-02 morning        9      40
           afternoon     13     100
2000-01-03 morning       14      50
           afternoon     18     100
2000-01-04 morning       17      40
           afternoon     19      50
'''

df2.resample('D', level=0).sum()
'''
            price  volume
2000-01-01     21     110
2000-01-02     22     140
2000-01-03     32     150
2000-01-04     36      90
'''

如果您想基于固定的时间戳调整容器的开始:

start, end = '2000-10-01 23:30:00', '2000-10-02 00:30:00'
rng = pd.date_range(start, end, freq='7min')
ts = pd.Series(np.arange(len(rng)) * 3, index=rng)
ts
'''
2000-10-01 23:30:00     0
2000-10-01 23:37:00     3
2000-10-01 23:44:00     6
2000-10-01 23:51:00     9
2000-10-01 23:58:00    12
2000-10-02 00:05:00    15
2000-10-02 00:12:00    18
2000-10-02 00:19:00    21
2000-10-02 00:26:00    24
Freq: 7T, dtype: int64
'''

ts.resample('17min').sum()
'''
2000-10-01 23:14:00     0
2000-10-01 23:31:00     9
2000-10-01 23:48:00    21
2000-10-02 00:05:00    54
2000-10-02 00:22:00    24
Freq: 17T, dtype: int64
'''

ts.resample('17min', origin='epoch').sum()
'''
2000-10-01 23:18:00     0
2000-10-01 23:35:00    18
2000-10-01 23:52:00    27
2000-10-02 00:09:00    39
2000-10-02 00:26:00    24
Freq: 17T, dtype: int64
'''

ts.resample('17min', origin='2000-01-01').sum()
'''
2000-10-01 23:24:00     3
2000-10-01 23:41:00    15
2000-10-01 23:58:00    45,                                 
2000-10-02 00:15:00    45
Freq: 17T, dtype: int64
'''

如果你想用偏移时间增量来调整bins的开始,下面两行是等效的:

ts.resample('17min', origin='start').sum()
'''
2000-10-01 23:30:00     9
2000-10-01 23:47:00    21
2000-10-02 00:04:00    54
2000-10-02 00:21:00    24
Freq: 17T, dtype: int64
'''

ts.resample('17min', offset='23h30min').sum()
'''
2000-10-01 23:30:00     9
2000-10-01 23:47:00    21
2000-10-02 00:04:00    54
2000-10-02 00:21:00    24
Freq: 17T, dtype: int64
'''

要替换弃用的base实参,现在可以使用offset,在这个例子中,它等价于base=2:

ts.resample('17min', offset='2min').sum()
'''
2000-10-01 23:16:00     0
2000-10-01 23:33:00     9
2000-10-01 23:50:00    36
2000-10-02 00:07:00    39
2000-10-02 00:24:00    24
Freq: 17T, dtype: int64
'''

要替换已弃用的loffset参数:

from pandas.tseries.frequencies import to_offset
loffset = '19min'
ts_out = ts.resample('17min').sum()
ts_out.index = ts_out.index + to_offset(loffset)
ts_out
'''
2000-10-01 23:33:00     0
2000-10-01 23:50:00     9
2000-10-02 00:07:00    21
2000-10-02 00:24:00    54
2000-10-02 00:41:00    24
Freq: 17T, dtype: int64
'''
  • 19
    点赞
  • 93
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值