How to introduce LAG time in Python?

How to introduce LAG time in Python?

This recipe helps you introduce LAG time in Python
In [1]:
## How to introduce LAG time in Python 
def Kickstarter_Example_46():
    print()
    print(format('How to introduce LAG time in Python','*^82'))
    import warnings
    warnings.filterwarnings("ignore")

    # Load library
    import pandas as pd

    # Create data frame
    df = pd.DataFrame()

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

    # Lag Time Data By One Row
    df['previous_days_stock_price'] = df['stock_price'].shift(1)

    # Show data frame
    print(); print(df)

    # Lag Time Data By Two Rows
    df['previous_days_stock_price'] = df['stock_price'].shift(2)

    # Show data frame
    print(); print(df)

Kickstarter_Example_46()
***********************How to introduce LAG time in Python************************

       dates  stock_price  previous_days_stock_price
0 2016-11-11          1.1                        NaN
1 2016-11-12          2.2                        1.1
2 2016-11-13          3.3                        2.2
3 2016-11-14          4.4                        3.3
4 2016-11-15          5.5                        4.4

       dates  stock_price  previous_days_stock_price
0 2016-11-11          1.1                        NaN
1 2016-11-12          2.2                        NaN
2 2016-11-13          3.3                        1.1
3 2016-11-14          4.4                        2.2
4 2016-11-15          5.5                        3.3


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
2 developers from Infosys
1 developer from Altimetrik
1 developer from Renovite Technologies
1 developer from ANAC
1 developer from KPMG
1 developer from Vodafone
1 developer from DXC Technology
1 developer from LTI
1 developer from YASH Technologies
1 developer from HvH