Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

pandas - Python : Return the missing weekdays dates and assign rate next to missing date

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/7/2019    1.0048
8/8/2019    0.97
8/9/2019    0.9659
8/12/2019   0.965

In the above dataframe, 29th July 2019 and 5th August 2019 are missing. These are weekdays. I need to populate the missing weekdays dates and assign the 'rate' which is next to missing date. For example: Assign the 30th july 2019 'rate' to the missing 29th july 2019 as well. Please suggest. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use for example pd.offsets.BDay() to get next business day.

Initial dataframe (the Dates column is of DateTime type):

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

Then:

df = df.merge(
        pd.DataFrame({'Dates':df['Dates'] + pd.offsets.BDay()}), on='Dates', how='outer'
    ).sort_values('Dates').bfill().dropna().reset_index(drop=True)

print(df)

Prints:

        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  1.0048
9  2019-08-08  0.9700
10 2019-08-09  0.9659
11 2019-08-12  0.9650

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...