假设我有一个如下构建的每周时间序列:
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
就会使两个每周系列不一致。如果重新采样可以接收到重新采样的时间索引,那就太好了,但据我所知这是不可能的。
你会怎么做?
最佳答案
@FLab 的答案是最好的,如果你想在两个系列上使用完全相同的索引,你也可以这样做:
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()
您可以在此处传递多个参数:
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)
关于python - 将 pandas 时间序列重新采样到预定义的网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42951719/