Skip to content Skip to sidebar Skip to footer

Calculate Difference Between Cells In Different Rows In A Pandas Dataframe

I have a dataframe in pandas like this: Timestamp ID X X Diff Y Y Diff 0 0 100 1.728 None 14.378 None 1 12 100 2.035 None 1

Solution 1:

Groupby 'ID' and calculate difference and then assign back to df:

df[['X diff','Y Diff']]=df.groupby('ID')[['X','Y']].diff()

output of df:

  Timestamp     ID      X        Y      X diff  Y Diff
0   0           100     1.728   14.378  NaN     NaN
1   12          100     2.035   14.378  0.307   0.000
2   24          100     2.342   14.378  0.307   0.000
3   36          100     2.630   14.378  0.288   0.000
4   48          100     2.937   14.416  0.307   0.038

Post a Comment for "Calculate Difference Between Cells In Different Rows In A Pandas Dataframe"