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 won't do often in the course, but its definitely good to know about this anyways!
Imports
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
Read Data
df = pd.read_csv('time_data/walmart_stock.csv',index_col='Date')
df.index = pd.to_datetime(df.index)
Alternatively,
df = pd.read_csv('time_data/walmart_stock.csv', index_col='Date', parse_dates=True)
df.head()
df.tail()
Use .shift(periods=1)
to shift data one position down if DateTime index is from earliest to latest. The default period is 1. Notice that NaN
shown on the first row
Before:
df.head()
After:
df.shift(1).head()
You will lose that last piece of data that no longer has an index!
Before:
df.tail()
After:
df.shift(1).tail()
df.head()
After:
df.shift(-1).head()
Before:
df.tail()
After:
df.shift(-1).tail()
df.head()
After:
df.tshift(periods=1,freq='M').head()