user2458922
user2458922

Reputation: 1721

With Pandas Calculate Diff , but with different columns

Give Data As

import pandas as pd
import numpy as np
df = pd.DataFrame({"Start": [1, 4, 8, 12], "Stop": [2, 6, 9, 13]})
# Calculate df['lag'] = Previous[Stop] - This[Start]

Lag = NA for first Row. Else Lag = Current Row Start - Previous Row Stop

Output:

df = pd.DataFrame({"Start": [1, 4, 8, 12], "Stop": [2, 6, 9, 13],"lag":[np.nan,2,2,3]})

Upvotes: 1

Views: 40

Answers (1)

It_is_Chris
It_is_Chris

Reputation: 14113

You are looking for shift

df['lag'] = df['Start'] - df['Stop'].shift()

   Start  Stop  lag
0      1     2  NaN
1      4     6  2.0
2      8     9  2.0
3     12    13  3.0

Upvotes: 3

Related Questions