Pandas: 将月中的日期转换为下个月的第 1 天

Pandas: convert date in month to the 1st day of next month

我想知道是否有任何有效的方法或单线,给定 pandas DatetimeIndex date1,return a DatetimeIndex date2那是下个月的第一天?

例如,如果 date1 是 '2011-09-30' 那么 date2 就是 '2011-10-01'?

我试过这一款衬垫

df.index.to_period("M").to_timestamp('M')

但这似乎只能return“同月的最后一天”。可以在这里做一些日期时间运算吗?

您可以使用pd.offsets.MonthBegin()

In [261]: d = pd.to_datetime(['2011-09-30', '2012-02-28'])

In [262]: d
Out[262]: DatetimeIndex(['2011-09-30', '2012-02-28'], dtype='datetime64[ns]', freq=None)

In [263]: d + pd.offsets.MonthBegin(1)
Out[263]: DatetimeIndex(['2011-10-01', '2012-03-01'], dtype='datetime64[ns]', freq=None)

您会在 official Pandas docs

中找到很多示例