Pandas Dataframe Question: Subtract next row and add specific value if NaN

Use groupby, diff and abs:

df['Results'] = abs(df.groupby('label')['Val'].diff(-1)).fillna(3)

  label  Val  Results
0     a    2      4.0
1     a    6      3.0
2     b    6     10.0
3     c    4      4.0
4     b   16      3.0
5     c    8      3.0

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top