Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sunday date imputation

Tags:

python

pandas

    Date
0   06-03-16
1   08-05-16
2   15-05-16
3   22-05-16
4   29-05-16
5   05-06-16
6   31-07-16

I have the above dates and some of the Dates are missing between 06-03-16 and 08-05-16. Every date is a Sunday and the missing dates are also Sundays. How to impute missing Sunday dates in a pandas data frame?

like image 735
user9023836 Avatar asked Jan 31 '26 13:01

user9023836


1 Answers

You can use pd.date_range selecting the mimimum and maximum dates as start and end respectively, and setting freq='W-SUN':

pd.DataFrame(pd.date_range(start=min(df.Date), end=max(df.Date), 
                           freq='W-SUN').strftime('%d-%m-%Y').tolist(), 
                           columns = ['Date'])

       Date
0   06-03-2016
1   13-03-2016
2   20-03-2016
3   27-03-2016
4   03-04-2016
5   10-04-2016
6   17-04-2016
7   24-04-2016
8   01-05-2016
9   08-05-2016
10  15-05-2016
11  22-05-2016
12  29-05-2016
13  05-06-2016
14  12-06-2016
15  19-06-2016
16  26-06-2016
17  03-07-2016
18  10-07-2016
19  17-07-2016
20  24-07-2016
21  31-07-2016

Make sure the Date column is in datetime format:

df.Date = pd.to_datetime(df.Date, format='%d-%m-%y')
like image 65
yatu Avatar answered Feb 03 '26 07:02

yatu