Python 在 Pandas 中为日期添加月份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46741423/
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
Add months to a date in Pandas
提问by mattblack
I'm trying to figure out how to add 3 months to a date in a Pandas dataframe, while keeping it in the date format, so I can use it to lookup a range.
我试图弄清楚如何在 Pandas 数据框中将日期添加 3 个月,同时将其保留为日期格式,以便我可以使用它来查找范围。
This is what I've tried:
这是我尝试过的:
#create dataframe
df = pd.DataFrame([pd.Timestamp('20161011'),
pd.Timestamp('20161101') ], columns=['date'])
#create a future month period
plus_month_period = 3
#calculate date + future period
df['future_date'] = plus_month_period.astype("timedelta64[M]")
However, I get the following error:
但是,我收到以下错误:
AttributeError: 'int' object has no attribute 'astype'
回答by Zero
You could use pd.DateOffset
你可以用 pd.DateOffset
In [1756]: df.date + pd.DateOffset(months=plus_month_period)
Out[1756]:
0 2017-01-11
1 2017-02-01
Name: date, dtype: datetime64[ns]
Another way using pd.offsets.MonthOffset
另一种使用方式 pd.offsets.MonthOffset
In [1785]: df.date + pd.offsets.MonthOffset(plus_month_period)
Out[1785]:
0 2016-10-14
1 2016-11-04
Name: date, dtype: datetime64[ns]
Details
细节
In [1757]: df
Out[1757]:
date
0 2016-10-11
1 2016-11-01
In [1758]: plus_month_period
Out[1758]: 3