pandas :将月份中的日期转换为下个月的第一天 [英] Pandas: convert date in month to the 1st day of next month

查看:108
本文介绍了 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)

您可以在官方熊猫中找到很多示例文档

这篇关于 pandas :将月份中的日期转换为下个月的第一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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