2017-07-07 44 views
0

以下是我具有esh->盈利驚喜歷史記錄 和sph->股票價格歷史記錄的以下數據框。在自定義條件下合併數據幀的高效方式

盈利驚喜歷史

ticker reported_date reported_time_code eps_actual 
0 ABC  2017-10-05  AMC    1.01 
1 ABC  2017-07-04  BMO    0.91 
2 ABC  2017-03-03  BMO    1.08 
3 ABC  2016-10-02  AMC    0.5 

股價歷史

ticker  date adj_open ad_close 
0 ABC  2017-10-06 12.10  13.11  
1 ABC  2017-12-05 11.11  11.87  
2 ABC  2017-12-04 12.08  11.40  
3 ABC  2017-12-03 12.01  13.03 
.. 
101 ABC  2017-07-04 9.01  9.59 
102 ABC  2017-07-03 7.89  8.19 

我喜歡通過合併其應具有以下幾列兩個數據集建立一個新的數據框下面還顯示,如果該reported_time_code從收益突擊歷史記錄是AMC那麼從股票價格歷史記錄中提取的記錄應該是第二天。如果reported_time_code是BM0然後記錄股票價格歷史記錄應該是同一天。如果我在esh的actual_reported列和sph的data列上使用直接合並函數,它將打破上述條件。尋找轉換數據

這裏的有效方式是產生變換的數據集

ticker  date  adj_open ad_close eps_actual 
0 ABC  2017-10-06 12.10  13.11  1.01 
101 ABC  2017-07-04 9.01  9.59  0.91 
+0

@ScottBoston糾正它! – user845405

回答

1

讓我們使用np.wheredrop不需要的列添加一個新列,「日期」,根據reported_time_code股價歷史數據幀然後merge賺取歷史數據幀:

eh['reported_date'] = pd.to_datetime(eh.reported_date) 

sph['date'] = pd.to_datetime(sph.date) 

eh_new = eh.assign(date=np.where(eh.reported_time_code == 'AMC', 
           eh.reported_date + pd.DateOffset(days=1), 
           eh.reported_date)).drop(['reported_date','reported_time_code'],axis=1) 

sph.merge(eh_new, on=['ticker','date']) 

輸出:

ticker  date adj_open ad_close eps_actual 
0 ABC 2017-10-06  12.10  13.11  1.01 
1 ABC 2017-07-04  9.01  9.59  0.91 
0

這是你的抵消只是一天是偉大的。然後你可以做如下事情:

mask = esh['reported_time_code'] == 'AMC' 
# The mask is basically an array of 0 and 1's \ 
    all we have to do is to convert them into timedelta objects standing for \ 
    the number of days to offset 

offset = mask.values.astype('timedelta64[D]') 
# The D inside the bracket stands for the unit of time to which \ 
    you want to attach your number. In this case, we want [D]ays. 

esh['date'] = esh['reported_date'] + offset 
esh.merge(sph, on=['ticker', 'date']).drop(['reported_date', 'reported_time_code'], \ 
              axis=1, inplace=True)