Title: Lag A Time Feature
Slug: lag_a_time_feature
Summary: How to lag a dates and times feature for machine learning in Python.
Date: 2017-09-11 12:00
Category: Machine Learning
Tags: Preprocessing Dates And Times
Authors: Chris Albon

Preliminaries


In [1]:
# Load library
import pandas as pd

Create Date Data


In [2]:
# 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


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

# Show data frame
df


Out[3]:
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