将pandas时间序列重新采样到预定义的网格

时间:2017-03-22 12:31:11

标签: python pandas time-series

假设我有一个像这样构建的每周时间序列:

rng = pd.date_range('1/1/2011', periods=72, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
weekly = ts.resample('W').mean()

你还有另一个每日间隔的系列,你也想每周聚集一次但是它与第一个系列相匹配。

rng2 = pd.date_range('17/1/2011', periods=72, freq='D')
ts2 = pd.Series(np.random.randn(len(rng2)), index=rng2)

请注意,第二个系列并非在同一天开始,因此只需重新采样ts2,这会导致每周两个系列不对齐。如果resample可以接收重新采样的检测时间索引会很好,但AFAICT这是不可能的。

你会怎么做?

2 个答案:

答案 0 :(得分:2)

重新采样到每周时,您还可以指定一周开始的那一天:http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offsets

因此你可以这样做:

ts2_resamples = ts2.resample(weekly.index.freq).mean()

答案 1 :(得分:2)

@FLab答案是最好的imo,如果你想在两个系列上使用完全相同的索引,你也可以这样做:

import pandas as pd
import numpy as np

rng = pd.date_range('1/1/2011', periods=72, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
weekly = ts.resample('W').mean()

rng2 = pd.date_range('17/1/2011', periods=72, freq='D')
ts2 = pd.Series(np.random.randn(len(rng2)), index=rng2)

ts2.reindex(ts.index).resample('W').mean()

Out[14]: 
2011-01-02         NaN
2011-01-09         NaN
2011-01-16         NaN
2011-01-23   -0.073253
2011-01-30   -0.065030
2011-02-06   -0.037297
2011-02-13    0.101782
2011-02-20   -0.386027
2011-02-27    0.131906
2011-03-06    0.107101
2011-03-13   -0.030496
Freq: W-SUN, dtype: float64

如果您无法访问先前的索引,只需使用@FLab方法即可:

ts.resample('W-SUN').mean()
ts2.resample('W-SUN').mean()

你可以在这里传递多个arg:

Alias   Description
W-SUN   weekly frequency (sundays). Same as ‘W’
W-MON   weekly frequency (mondays)
W-TUE   weekly frequency (tuesdays)
W-WED   weekly frequency (wednesdays)
W-THU   weekly frequency (thursdays)
W-FRI   weekly frequency (fridays)
W-SAT   weekly frequency (saturdays)