Using pandas.date_range () to generate multiple dates, two dates per week
I use pd.date_range(start_date, end_date, freq='W-MON')
to generate weekly frequency dates every Monday between start_date=2017-01-01
and end_date=2017-12-31
, which means about 4 days are generated per month. How do I generate 8 dates per month and not generate 2 times a week, but on different days per week, say Monday and any other day other than Saturday or Sunday?
source to share
There are at least two ways to achieve this:
1) You can choose a weekly frequency corresponding to another day of the week and take union
from them that sorts the indices nicely and adds them.
start_date = "2017-01-01"
end_date = "2017-12-31"
d1 = pd.date_range(start_date, end_date, freq="W-MON")
d2 = pd.date_range(start_date, end_date, freq="W-TUE")
d1.union(d2)
2) The simplest way would be to create an offset corresponding to the additional one Day
. It is followed by the same operations union
.
from pandas.tseries.offsets import Day
d1.union(d1 + Day(1))
Both approaches create:
DatetimeIndex(['2017-01-02', '2017-01-03', '2017-01-09', '2017-01-10',
'2017-01-16', '2017-01-17', '2017-01-23', '2017-01-24',
'2017-01-30', '2017-01-31',
...
'2017-11-27', '2017-11-28', '2017-12-04', '2017-12-05',
'2017-12-11', '2017-12-12', '2017-12-18', '2017-12-19',
'2017-12-25', '2017-12-26'],
dtype='datetime64[ns]', length=104, freq=None)
source to share