18 KiB
Time Shifting¶
Sometimes you may need to shift all your data up or down along the time series index. In fact, a lot of pandas built-in methods do this under the hood. This isn't something we'll do often in the course, but it's definitely good to know about this anyways!
import pandas as pd
df = pd.read_csv('../Data/starbucks.csv',index_col='Date',parse_dates=True)
df.head()
df.tail()
.shift() forward¶
This method shifts the entire date index a given number of rows, without regard for time periods (months & years).
It returns a modified copy of the original DataFrame.
df.shift(1).head()
# NOTE: You will lose that last piece of data that no longer has an index!
df.shift(1).tail()
.shift() backwards¶
df.shift(-1).head()
df.shift(-1).tail()
Shifting based on Time Series Frequency Code¶
We can choose to shift index values up or down without realigning the data by passing in a freq argument.
This method shifts dates to the next period based on a frequency code. Common codes are 'M' for month-end and 'A' for year-end.
Refer to the Time Series Offset Aliases table from the Time Resampling lecture for a full list of values, or click here.
# Shift everything forward one month
df.shift(periods=1, freq='M').head()
For more info on time shifting visit http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html
Up next we'll look at rolling and expanding!