-->

Pandas date_range for six-monthly values

2019-07-31 09:19发布

问题:

I'm trying to create a date range which works in six-month increments backwards from a particular date. So if the end_date is 2020/01/15, then the date before that would be 2019/07/15, then 2019/01/15, etcetera.

pandas accepts, say, '6M' as the freq parameter in date_range, but this actually means month-end, so

test_range=pd.date_range(periods=10,end=dt.date(2020,1,15),freq='6M')

returns

DatetimeIndex(['2015-06-30', '2015-12-31', '2016-06-30', '2016-12-31',
               '2017-06-30', '2017-12-31', '2018-06-30', '2018-12-31',
               '2019-06-30', '2019-12-31'],
              dtype='datetime64[ns]', freq='6M')

Which defaults to year-end/june-end and so isn't really what I need. Does date_range have the functionality to work backwards in monthly (or six-monthly) increments from a given date? If it does I haven't been able to find it.

Thanks in advance for any help!

回答1:

Try to use SMS (semi-month start frequency (1st and 15th)) frequency:

In [109]: test_range=pd.date_range(periods=10,end='2020-01-15',freq='6SMS')

In [110]: test_range
Out[110]:
DatetimeIndex(['2017-10-15', '2018-01-15', '2018-04-15', '2018-07-15', '2018-10-15', '2019-01-15', '2019-04-15', '2019-07-15',
               '2019-10-15', '2020-01-15'],
              dtype='datetime64[ns]', freq='6SMS-15')

you can use a custom frequency as well:

In [130]: d = dt.date(2019,12,11)

In [131]: pd.date_range(periods=5,end=d,freq='6SMS-{}'.format(d.day))
Out[131]: DatetimeIndex(['2018-12-11', '2019-03-11', '2019-06-11', '2019-09-11', '2019-12-11'], dtype='datetime64[ns]', freq='6SMS-11')

another solution:

In [145]: pd.date_range(periods=5,end=d,freq='6MS') + pd.offsets.Day(d.day-1)
Out[145]: DatetimeIndex(['2017-12-11', '2018-06-11', '2018-12-11', '2019-06-11', '2019-12-11'], dtype='datetime64[ns]', freq=None)