Python / Pandas - DataFrame索引 - 向前移动一个月

时间:2016-01-29 22:37:15

标签: python datetime pandas timestamp

我有一个DataFrame:

                Actual       Pred
Date                             
2005-04-01        10.2  10.364470
2005-05-01         9.4   9.542778
2005-06-01         9.5   9.684794
2005-07-01         9.4   9.547604
2005-08-01         9.7   9.768893

我想为每个DataFrame的索引添加一个月,所以它看起来像这样:

                Actual       Pred
Date                             
2005-05-01        10.2  10.364470
2005-06-01         9.4   9.542778
2005-07-01         9.5   9.684794
2005-08-01         9.4   9.547604
2005-09-01         9.7   9.768893

我该怎么做?

重要评论:

当我命令print type(DataFrame.index[0])找出索引的数据类型时,我得到:

<class 'pandas.tslib.Timestamp'>

只是为了让你知道它是熊猫时间戳。

1 个答案:

答案 0 :(得分:6)

您可以使用pd.DateOffset

In [82]: df
Out[82]: 
            Actual       Pred
Date                         
2005-04-01    10.2  10.364470
2005-05-01     9.4   9.542778
2005-06-01     9.5   9.684794
2005-07-01     9.4   9.547604
2005-08-01     9.7   9.768893

df.index = df.index + pd.DateOffset(months=1)

In [85]: df
Out[85]: 
            Actual       Pred
Date                         
2005-05-01    10.2  10.364470
2005-06-01     9.4   9.542778
2005-07-01     9.5   9.684794
2005-08-01     9.4   9.547604
2005-09-01     9.7   9.768893