Dennis
Dennis

Reputation: 215

How to get all weeks between two dates?

I have dataframe just_dates:

0     2003-01-02
1     2015-10-31
2     2015-11-01
16    2015-11-02
33    2015-11-03
44    2015-11-04

and a dataframe weeks which I calculated with

df['weeks'] = pd.PeriodIndex(df.just_dates, freq='W')

weeks looks like:

0    2002-12-30/2003-01-05
1    2015-10-26/2015-11-01
2    2015-10-26/2015-11-01
16   2015-11-02/2015-11-08
33   2015-11-02/2015-11-08
44   2015-11-02/2015-11-08

Now I want to have a data frame with all the weeks between the first and the last week, so all_weeks should look like:

0  2002-12-30/2003-01-05
1  2003-01-06/2003-01-12
2  2003-01-13/2003-01-19
...
   2015-10-26/2015-11-01
   2015-10-26/2015-11-01
   2015-11-02/2015-11-08
   2015-11-02/2015-11-08
   2015-11-02/2015-11-08

Is there an easy way to do this?

Upvotes: 2

Views: 1292

Answers (1)

Chris Adams
Chris Adams

Reputation: 18647

Use pandas.period_range:

pd.DataFrame(pd.period_range(start=df.weeks.min(),
                             end=df.weeks.max(),
                             freq='W'))

[out]

                         0
0    2002-12-30/2003-01-05
1    2003-01-06/2003-01-12
2    2003-01-13/2003-01-19
3    2003-01-20/2003-01-26
4    2003-01-27/2003-02-02
5    2003-02-03/2003-02-09
..                     ...
665  2015-09-28/2015-10-04
666  2015-10-05/2015-10-11
667  2015-10-12/2015-10-18
668  2015-10-19/2015-10-25
669  2015-10-26/2015-11-01
670  2015-11-02/2015-11-08

[671 rows x 1 columns]

Upvotes: 5

Related Questions