简体   繁体   English

如何将pandas.dataframe的索引提高四分之一?

[英]How can I advance the index of a pandas.dataframe by one quarter?

I would like to shift the index of a pandas.dataframe by one quarter. 我想将pandas.dataframe的索引移动四分之一。 The dataframe looks like: 数据框如下所示:

            ID   Nowcast  Forecast
1991-01-01   35   4144.70   4137.40
1991-01-01   40   4114.00   4105.00
1991-01-01   60   4135.00   4130.00
....

So far, I calculate the number of occurrences of the first timestamp 1991-01-01 and shifted the dataframe accordingly. 到目前为止,我计算了第一个时间戳1991-01-01的出现次数,并相应地移动了数据帧。 The code is: 代码是:

Stamps = df.index.unique()
zero = 0
for val in df.index:
    if val == Stamps[0]:
        zero = zero + 1
df = df.shift(zero)

The operation results in the following dataframe: 该操作导致以下数据框:

              ID   Nowcast  Forecast 
1991-04-01   35.0   4144.70   4137.40       
1991-04-01   40.0   4114.00   4105.00       
1991-04-01   60.0   4135.00   4130.00  

The way I'm doing this strikes me as inefficient and error-prone. 我这样做的方式使我感到效率低下且容易出错。 Is there a better way? 有没有更好的办法?

you can use pd.DateOffset() : 您可以使用pd.DateOffset()

In [110]: df
Out[110]:
            ID  Nowcast  Forecast
1991-01-01  35   4144.7    4137.4
1991-01-01  40   4114.0    4105.0
1991-01-01  60   4135.0    4130.0

In [111]: df.index += pd.DateOffset(months=3)

In [112]: df
Out[112]:
            ID  Nowcast  Forecast
1991-04-01  35   4144.7    4137.4
1991-04-01  40   4114.0    4105.0
1991-04-01  60   4135.0    4130.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM