[英]Resampling pandas time series to a predefined grid
假設我有一個這樣的每周時間序列:
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
重新采樣,就會使兩個每周的系列不一致。 如果重采樣可以接收到一個detetime索引進行重采樣,那就太好了,但是AFAICT不可能。
你會怎么做?
重新采樣為每周時,您還可以指定一周中的哪一天開始: http : //pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offsets 。
因此,您可以執行以下操作:
ts2_resamples = ts2.resample(weekly.index.freq).mean()
@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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.