I would like to shift the index of a pandas.dataframe by one quarter. 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. 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() :
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.