Skip to main content
 首页 » 编程设计

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

2025年05月04日16bluestorm

我有一个数据框:

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

只是为了让您知道这是一个 Pandas 时间戳。

请您参考如下方法:

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