如何获得两个日期之间的所有星期?

时间:2019-06-10 14:31:59

标签: python pandas

我有数据框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

和我用来计算的数据帧weeks

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

weeks如下:

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

现在,我希望有一个数据框,其中包含第一周和最后一周之间的所有周,因此all_weeks应该看起来像:

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

有一种简单的方法吗?

1 个答案:

答案 0 :(得分:4)

使用pandas.period_range

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

[出]

                         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]