Search code examples
pythonpandasdivide

Pandas - Division within a single column issue


I have a column of float64 data indexed by datetime. I need to divide one row by the row before it.

In the instance below I would need to start in the dataframe with 1.1133/1.1134 then take the result and store it in a new column. Then move down a row and repeat.

In excel you can do this very easy say B2/B3 and drag it down. Is there a method I can use in a Pandas Dataframe to mimic this? I have tried various configs with the divide function, but to no good result. Any help on this would be great to point me in the right direction.

Time             Close

4/26/2019 11:08 1.1133 

4/26/2019 11:07 1.1134

4/26/2019 11:06 1.1135

4/26/2019 11:05 1.1135

4/26/2019 11:04 1.1135

4/26/2019 11:03 1.1135

Solution

  • You can do this in three steps:

    1. Duplicate dataFrame
    2. Shift the duplicate dataframe (move index by one row)
    3. Create new column based on substraction

    df["new_columns"] = (df["Close"] / df["Close"].shift(1))
    

    I am am not exactly sure if you are looking shift(1) or shift(-1) shift move all index by the given value.