Python 在熊猫中为日期添加月份

Python 在熊猫中为日期添加月份,python,pandas,date,Python,Pandas,Date,我正试图找出如何在Pandas数据框中为日期添加3个月,同时保持日期格式,以便使用它查找范围 这就是我尝试过的: #create dataframe df = pd.DataFrame([pd.Timestamp('20161011'), pd.Timestamp('20161101') ], columns=['date']) #create a future month period plus_month_period = 3 #calculate

我正试图找出如何在Pandas数据框中为日期添加3个月,同时保持日期格式,以便使用它查找范围

这就是我尝试过的:

#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]")
但是,我得到以下错误:

AttributeError: 'int' object has no attribute 'astype'

您可以使用
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]
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]
另一种方法是使用
pd.offset.MonthOffset

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]
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]

细节

In [1757]: df
Out[1757]:
        date
0 2016-10-11
1 2016-11-01

In [1758]: plus_month_period
Out[1758]: 3

假设您有以下格式的数据框,其中必须向日期列添加整数月份

开始日期 月至月加 2014-06-01 23 2014-06-01 4. 2000-10-01 10 2016-07-01 3. 2017-12-01 90 2019-01-01 2.
pd.offsets.MonthOffset没有如结果所示添加月份。它为我增加了天数,如图所示。现在更通用的解决方案是从pandas.tseries.offsets导入DateOffset,然后是
+DateOffset(months=1)