So, there is an initial DF:

Com Res 1 5 1 6 1 6 1 5 1 4 2 5 2 6 2 8 2 7

It is necessary for each individual Com value to create a column that shows the delta Res . That is, at the output you need to get this:

Com Res Delta 1 5 - 1 6 1 1 6 0 1 5 -1 1 4 -1 2 5 - 2 6 1 2 8 2 2 7 -1

1 answer 1

To achieve this result, you can group the data frame by the "Com" column using the groupby() method and apply the diff() method to the "Res" column, which for each group calculates the difference between adjacent elements.

 df['Delta'] = df.groupby('Com')['Res'].diff() df['Delta'] = df['Delta'].fillna('-') # Заполним пустые значения '-'