Return the consecutive missing weekdays dates and assign rate next to missing dates

前端 未结 1 1360
旧巷少年郎
旧巷少年郎 2021-01-17 07:24
Dates       rates
7/26/2019   1.04
7/30/2019   1.0116
7/31/2019   1.005
8/1/2019    1.035
8/2/2019    1.01
8/6/2019    0.9886
8/12/2019   0.965

df = df.merge(
    p         


        
1条回答
  •  别那么骄傲
    2021-01-17 07:34

    Try option 1 as below which includes creating a new df & merging it (the route you are already on)

    or option 2 as suggested by @piRSquared (bfill() instead of ffill())

    df['Dates'] = pd.to_datetime(df['Dates'])
    a=pd.DataFrame({'Dates':pd.bdate_range('2019-07-26', '2019-08-12')})
    df.merge(a, on='Dates', how='outer').sort_values('Dates').bfill().dropna().reset_index(drop=True) 
    

    Output

            Dates   rates
    0   2019-07-26  1.0400
    1   2019-07-29  1.0116
    2   2019-07-30  1.0116
    3   2019-07-31  1.0050
    4   2019-08-01  1.0350
    5   2019-08-02  1.0100
    6   2019-08-05  0.9886
    7   2019-08-06  0.9886
    8   2019-08-07  0.9650
    9   2019-08-08  0.9650
    10  2019-08-09  0.9650
    11  2019-08-12  0.9650
    
    df.set_index('Dates').asfreq('B').bfill().reset_index()
    

    Output

             Dates  rates
    0   2019-07-26  1.0400
    1   2019-07-29  1.0116
    2   2019-07-30  1.0116
    3   2019-07-31  1.0050
    4   2019-08-01  1.0350
    5   2019-08-02  1.0100
    6   2019-08-05  0.9886
    7   2019-08-06  0.9886
    8   2019-08-07  0.9650
    9   2019-08-08  0.9650
    10  2019-08-09  0.9650
    11  2019-08-12  0.9650
    

    0 讨论(0)
提交回复
热议问题