在Pandas中为日期添加月份

2024-04-25 16:42:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出如何在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'

有什么办法吗?谢谢!


Tags: 数据dataframepandasdfdate格式createplus
1条回答
网友
1楼 · 发布于 2024-04-25 16:42:49

你可以用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]

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

细节

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

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

相关问题 更多 >

    热门问题