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

限于喜欢 提交于 2019-11-26 21:35:16

问题


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?

For example, if date1 is '2011-09-30' then date2 is '2011-10-01'?

I have tried this one liner

    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?

Thanks!


回答1:


You can use 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)

You'll find a lot of examples in the official Pandas docs



来源:https://stackoverflow.com/questions/43636171/pandas-convert-date-in-month-to-the-1st-day-of-next-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!