2017-06-07 31 views
0

我需要基于日期时间范围加入2个数据帧。 我已经为它搜索/堆栈并找到了一些可能的解决办法。熊猫。以数据范围加入重新采样的df与原始df

由于我重新采样数据并希望将聚合版本加入原始数据,我认为可能有一种方法可以通过添加代表可能的聚集日期时间的“连接标准列”来模拟重新采样。

这是我的基地:

import pandas as pd 
import numpy as np 
import quandl 

df = quandl.get("WIKI/GOOGL") 
df = df.ix[:, ['Close']] 

print('***************** ORIG') 
print(df.head(10).to_string()) 

ac = df['Close'].resample('3D').mean() 

print('***************** RESAMPLED') 
print(ac.head(10).to_string()) 


frames = [ac] 
ac2 = pd.concat(frames, axis=1, join='inner') 

print('***************** RESAMPLED 2') 
print(ac2.head(10).to_string()) 



#new = pd.merge(df, ac2, on=df.index, how='left') 

#print('***************** JOIN') 
#print(new.to_string()) 

,这是输出:

***************** ORIG 
       Close 
Date    
2004-08-19 100.335 
2004-08-20 108.310 
2004-08-23 109.400 
2004-08-24 104.870 
2004-08-25 106.000 
2004-08-26 107.910 
2004-08-27 106.150 
2004-08-30 102.010 
2004-08-31 102.370 
2004-09-01 100.250 
***************** RESAMPLED 
Date 
2004-08-19 104.322500 
2004-08-22 107.135000 
2004-08-25 106.686667 
2004-08-28 102.010000 
2004-08-31 101.376667 
2004-09-03 100.010000 
2004-09-06 101.940000 
2004-09-09 103.820000 
2004-09-12 109.495000 
2004-09-15 114.486667 
Freq: 3D 

很酷会,如果我能计算出新的列

***************** ORIG 
       Close newDate 
Date    
2004-08-19 100.335 2004-08-19 
2004-08-20 108.310 2004-08-19 
2004-08-23 109.400 2004-08-22 
2004-08-24 104.870 2004-08-22 
2004-08-25 106.000 2004-08-25 
2004-08-26 107.910 2004-08-25 
2004-08-27 106.150 2004-08-25 
2004-08-30 102.010 2004-08-28 
2004-08-31 102.370 2004-08-31 
2004-09-01 100.250 2004-08-31 

和使用这是一个加入标准...

但我不急于重新编程循环中的resample ...如果你想建议... :)

任何想法?

谢谢! E.

****编辑**** 我找到了解决方案来转移日期。现在我能加入:)

print('***************** RESAMPLED 2') 
ac2['folgep'] = ac2.index.shift(1) 
ac2['DatumJoin'] = ac2.index 
print(ac2.head(10).to_string()) 


df['matched'] = np.piecewise(df.index, [(df.index >= start_date)&(df.index <= end_date) for start_date, end_date in zip(ac2.index, ac2.folgep.values)], ac2.DatumJoin) 

print('***************** after join') 
print(df.head(10).to_string()) 

回答

0

你可以简单地reindex您重新采样数据:

df['Close3D'] = df.Close.resample('3D').mean().reindex(df.index, method='ffill') 
+0

伟大的解决方案!无需加入:)谢谢! @emulbreh – Ele