How do I repeat a DatetimeIndex in pandas

Viewed 235

How do I create a repeating date range? For example, I would like the following to repeat three times

rng = pd.date_range('1/1/2011', periods=3, freq='W')

Expected output:
2011-01-02
2011-01-09
2011-01-16
2011-01-02
2011-01-09
2011-01-16
2011-01-02
2011-01-09
2011-01-16

I have tried:

rng = pd.concat([rng] * 3, axis=1) #which does not work with dates
rng = np.repeat(rng,3) #this repeats each date three times instead of the list three times?

3 Answers

We can use np.tile and wrap with DatetimeIndex to keep type if needed:

rng = pd.DatetimeIndex(
    np.tile(pd.date_range('1/1/2011', periods=3, freq='W'), 3)
)

rng:

DatetimeIndex(['2011-01-02', '2011-01-09', '2011-01-16', '2011-01-02',
               '2011-01-09', '2011-01-16', '2011-01-02', '2011-01-09',
               '2011-01-16'],
              dtype='datetime64[ns]', freq=None)

Try with reduce

import functools
functools.reduce(pd.Index.append,[rng]*3)
Out[70]: 
DatetimeIndex(['2011-01-02', '2011-01-09', '2011-01-16', '2011-01-02',
               '2011-01-09', '2011-01-16', '2011-01-02', '2011-01-09',
               '2011-01-16'],
              dtype='datetime64[ns]', freq=None)

You can just use concat function to PD series

rng = pd.date_range('1/1/2011', periods=3, freq='W').to_series(index=[0,1,2])
pd.concat([rng]*3)
Related