Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

python - Pandas Date Range Monthly on Specific Day of Month

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

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...