Search code examples
pythonpandascumsum

Pandas : reverse cumulative sum's process


I've got a simple pandas' Serie, like this one :

    st
0   74
1   91
2   105
3   121
4   136
5   157

Datas for this Serie are the result of a cumulative sum, so I was wondering if a pandas function could "undo" the process, and return a new Serie like :

    st     result
0   74     74
1   91     17
2   105    14
3   121    16
4   136    15
5   157    21

result[0] = st[0], but after result[i] = st[i]-st[i-1]. 

It's seemed to be very simple (and maybe I missed a post), but I didn't find anything...


Solution

  • Use Series.diff with replace first missing value by original by Series.fillna and then if necessary cast to integers:

    df['res'] = df['st'].diff().fillna(df['st']).astype(int)
    print (df)
        st  res
    0   74   74
    1   91   17
    2  105   14
    3  121   16
    4  136   15
    5  157   21