v Lag A Time Feature - Machine Learning

Lag A Time Feature

Preliminaries

# Load library
import pandas as pd

Create Date Data

# Create data frame
df = pd.DataFrame()

# Create data
df['dates'] = pd.date_range('1/1/2001', periods=5, freq='D')
df['stock_price'] = [1.1,2.2,3.3,4.4,5.5]

Lag Time Data By One Row

# Lagged values by one row
df['previous_days_stock_price'] = df['stock_price'].shift(1)

# Show data frame
df
dates stock_price previous_days_stock_price
0 2001-01-01 1.1 NaN
1 2001-01-02 2.2 1.1
2 2001-01-03 3.3 2.2
3 2001-01-04 4.4 3.3
4 2001-01-05 5.5 4.4