pandas 熊猫:将月份中的日期转换为下个月的第一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43636171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: convert date in month to the 1st day of next month
提问by yuqli
I am wondering if there are any efficient methods or one-liner that, given a pandas DatetimeIndex date1, return a DatetimeIndex date2that is the first day of the next month?
我想知道是否有任何有效的方法或单行程序,给定一个 Pandas DatetimeIndex date1,返回一个 DatetimeIndex date2是下个月的第一天?
For example, if date1is '2011-09-30' then date2is '2011-10-01'?
例如,如果date1是“2011-09-30”,那么date2是“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!
谢谢!
回答by MaxU
You can use pd.offsets.MonthBegin()
您可以使用 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
你会在Pandas 官方文档中找到很多例子