2017-10-21 103 views
-1

我有以下兩個數據框。 DF1:python找到附近的日期 - 3例

date  customers 
2017-10-09  8 
2017-10-10  5 
2017-10-11  4 
2017-10-12  8 
2017-10-13  9 
2017-10-16  1 

DF2:

date   manager prev_day next_day on_or_next_day 
2017-10-10 george 
2017-10-14 fred 

我需要一個函數,將在DF2完成剩餘的三列。列的邏輯是這樣的: prev_day - 在df1之前發生在df1之前的日期['date'] next_day - 在df1之後在df1發生的下一個日期['date'] on_or_next_day - if df2 [''日期']在DF1然後把該否則可用的下一個日期DF1

基於功能上面的例子應該返回DF2如下:

date   manager prev_day next_day  on_or_next_day 
2017-10-10 george 2017-10-09 2017-10-11 2017-10-10 
2017-10-14 fred  2017-10-13 2017-10-16 2017-10-16 

正如上面你會發現,週末是排除在這個例子,但在真實的數據框中有幾天,當商店被關閉等等,所以使用BDay或類似的東西不起作用,你需要從日期列表d F2。

任何你不確定的事情,請隨時詢問,因爲我一直在爭取這個多年,現在不能得到一個pythonic解決方案。

+0

獲得「pythonic解決方案」本身並不是目的。如果您有任何解決方案,那沒關係,請在[codereview.se]詢問是否可以根據需要進行改進。 –

+0

不清楚你在問什麼。爲了解決你的問題(那麼它的主題太寬泛/基於觀點/未來的讀者沒用(因爲問題不是反覆出現的))?遇到某個特定位的問題(然後重新提出問題以詢問位並將您的任務作爲背景細節)? –

回答

2

我單獨做用merge_asof

df['NewDate']=df.date 

NEXT_DAY:

pd.merge_asof(df1,df.drop('customers',1),on='date',direction='forward',allow_exact_matches =False).rename(columns={'NewDate':'next_day'}) 
    Out[136]: 
      date manager next_day 
    0 2017-10-10 george 2017-10-11 
    1 2017-10-14 fred 2017-10-16 

prev_day:

pd.merge_asof(df1,df.drop('customers',1),on='date',direction='backward',allow_exact_matches =False).rename(columns={'NewDate':'prev_day'}) 
Out[138]: 
     date manager prev_day 
0 2017-10-10 george 2017-10-09 
1 2017-10-14 fred 2017-10-13 

on_or_next_day:

pd.merge_asof(df1,df.drop('customers',1),on='date',direction='forward',allow_exact_matches =True).rename(columns={'NewDate':'on_or_next_day'}) 
Out[141]: 
     date manager on_or_next_day 
0 2017-10-10 george  2017-10-10 
1 2017-10-14 fred  2017-10-16