pandas :将月份中的日期转换为下个月的第一天
问题描述:
我想知道是否有任何有效的方法或单行代码,在给定熊猫DatetimeIndex date1 的情况下,返回DatetimeIndex date2 ,这是下一天的第一天一个月?
I am wondering if there are any efficient methods or one-liner that, given a pandas DatetimeIndex date1, return a DatetimeIndex date2 that is the first day of the next month?
例如,如果 date1 是'2011-09-30',那么 date2 是'2011-10-01'?
For example, if date1 is '2011-09-30' then date2 is '2011-10-01'?
我已经尝试过这种衬纸
df.index.to_period("M").to_timestamp('M')
但这似乎只能返回同一月的最后一天".可以在这里做一些日期时间算法吗?
But this seems only able to return the "last day of the same month". Is it possible to do some datetime arithmetic here?
谢谢!
答
您可以使用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)
您可以在官方熊猫中找到很多示例文档