pandas 的date_range为六个月的值 [英] Pandas date_range for six-monthly values
问题描述
我正在尝试创建一个日期范围,该日期范围从特定日期开始向后六个月递增.因此,如果end_date是2020/01/15,那么之前的日期将是2019/07/15,然后是2019/01/15,等等.
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接受"6M"作为date_range中的freq参数,但这实际上表示月末,所以
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')
返回
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')
哪个默认为年末/年终,所以这不是我真正需要的. date_range是否具有从给定日期起每月(或每六个月)递增的功能?如果没有,我找不到它.
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.
在此先感谢您的帮助!
推荐答案
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')
另一种解决方案:
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)
这篇关于 pandas 的date_range为六个月的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!