pandas 的日期范围,每月的特定日期 [英] Pandas Date Range Monthly on Specific Day of Month

查看:132
本文介绍了 pandas 的日期范围,每月的特定日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Pandas中,我知道您可以使用锚点偏移量来指定更复杂的引用:
http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offset

In Pandas, I know you can use anchor offsets to specify more complicated reucrrences: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offset

我想指定一个date_range,使其在每个月的第n天为每月一次。最好的语法是什么?我正在想象与此类似的东西,它指定在星期五每2周重复一次:

I want to specify a date_range such that it is monthly on the nth day of each month. What is the best syntax to do that with? I'm imaginging something similar to this which specifies a recurrence every 2 weeks on Friday:

schedule = pd.date_range(start=START_STR, periods=26, freq="2W-FRI")


推荐答案

IIUC,您可以这样操作:

IIUC you can do it this way:

In [18]: pd.DataFrame(pd.date_range('2016-01-01', periods=10, freq='MS') + pd.DateOffset(days=26), columns=['Date'])
Out[18]:
        Date
0 2016-01-27
1 2016-02-27
2 2016-03-27
3 2016-04-27
4 2016-05-27
5 2016-06-27
6 2016-07-27
7 2016-08-27
8 2016-09-27
9 2016-10-27

更新:以说明月份和leap年的不同天数:

UPDATE: to account for different numbers of days of months and leap years:

def month_range(start, periods=12):
    rng = pd.date_range(pd.Timestamp(start)-pd.offsets.MonthBegin(),
                        periods=periods,
                        freq='MS')
    ret = (rng + pd.offsets.Day(pd.Timestamp(start).day-1)).to_series()
    ret.loc[ret.dt.month > rng.month] -= pd.offsets.MonthEnd(1)
    return pd.DatetimeIndex(ret)






示例:


Examples:

In [202]: month_range('2016-01-27', 12)
Out[202]:
DatetimeIndex(['2016-01-27', '2016-02-27', '2016-03-27', '2016-04-27', '2016-05-27', '2016-06-27', '2016-07-27', '2016-08-27',
               '2016-09-27', '2016-10-27', '2016-11-27', '2016-12-27'],
              dtype='datetime64[ns]', freq=None)

In [203]: month_range('2020-01-31', 12)
Out[203]:
DatetimeIndex(['2020-01-31', '2020-02-29', '2020-03-31', '2020-04-30', '2020-05-31', '2020-06-30', '2020-07-31', '2020-08-31',
               '2020-09-30', '2020-10-31', '2020-11-30', '2020-12-31'],
              dtype='datetime64[ns]', freq=None)

In [204]: month_range('2019-01-29', 12)
Out[204]:
DatetimeIndex(['2019-01-29', '2019-02-28', '2019-03-29', '2019-04-29', '2019-05-29', '2019-06-29', '2019-07-29', '2019-08-29',
               '2019-09-29', '2019-10-29', '2019-11-29', '2019-12-29'],
              dtype='datetime64[ns]', freq=None)

这篇关于 pandas 的日期范围,每月的特定日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆