2016-03-15 73 views
1

我尋找一種矢量溶液到計算與日期偏移的移動平均值。我有一個不規則間隔時間序列的成本對產品和每個價值,我想計算的前三個值的平均值,帶有日期的45天內偏移。例如,如果這是我的輸入數據幀:移動平均值與時間偏移熊貓

In [1]: df 
    Out [1]: 
     ActCost OrDate 
    0 8  2015-01-01 
    1 5  2015-02-04 
    2 10  2015–02-11 
    3 1  2015-02-11 
    4 10  2015-03-11 
    5 18  2015-03-15 
    6 20  2015-05-18 
    7 25  2015-05-23 
    8 8  2015-06-11 
    9 5  2015-10-09 
    10 15  2015-11-02 
    12 18  2015-12-20 

輸出將是:

In[2]: df 
    Out[2]: 
     ActCost OrDate  EstCost 
    0 8  2015-01-01 NaN 
    1 5  2015-02-04 NaN 
    2 10  2015–02-11 NaN 
    3 1  2015-02-11 NaN 
    4 10  2015-03-11 NaN 
    5 18  2015-03-15 NaN 
    6 20  2015-05-18 9.67 # mean(index 3:5) 
    7 25  2015-05-23 9.67 # mean(index 3:5) 
    8 8  2015-06-11 9.67 # mean(index 3:5) 
    9 5  2015-10-09 17.67 # mean(index 6:8) 
    10 15  2015-11-02 17.67 # mean(index 6:8) 
    12 18  2015-12-20 12.67 # mean(index 7:9) 

我目前的解決方案是:

for index, row in df.iterrows(): 
     orDate=row['OrDate'] 
     costsLanded = orDate - timedelta(45) 
     if costsLanded <= np.min(df.OrDate): 
      df.loc[index,'EstCost']=np.nan 
      break 
     if len(dfID[df.OrDate <= costsLanded]) < 3: 
      df.loc[index,'EstCost'] = np.nan 
      break 
     df.loc[index,'EstCost']=np.mean(df[‘ActShipCost'][df.OrDate <=   
              costsLanded].head(3)) 

我的代碼工作,但相當緩慢,而且我擁有數百萬的這些時間系列。我希望有人能就如何加快這個過程給我一些建議。我想,做的最好的事情是向量化的操作,但我不知道如何實現這一點。 非常感謝您的幫助!

+0

什麼'df.rolling(窗口= -45).mean()'? 0.18中的新功能使用'pd.rolling_window'作爲早期版本的熊貓。 – pbreach

+0

首先,你需要重新取樣,以一定時間間隔。 – pbreach

回答

0

嘗試是這樣的:

#Set up DatetimeIndex (easier to just load in data with index as OrDate) 
df = df.set_index('OrDate', drop=True) 
df.index = pd.DatetimeIndex(df.index) 
df.index.name = 'OrDate' 

#Save original timestamps for later 
idx = df.index 

#Make timeseries with regular daily interval 
df = df.resample('d').first() 

#Take the moving mean with window size of 45 days 
df = df.rolling(window=45, min_periods=0).mean() 

#Grab the values for the original timestamp and put the index back 
df = df.ix[idx].reset_index() 
0

如果我理解正確的話,我認爲你想要的是

df.resample('45D').agg('mean')