Python - Pandas - Unroll / Remove Cumulative Sum

前端 未结 2 858
长情又很酷
长情又很酷 2021-01-06 00:45

I have a data frame like the following (specific data below, this is generic). The no gives me a cumulative sum:

                 no
name day           
Jack         


        
相关标签:
2条回答
  • 2021-01-06 01:03

    If I understand correctly you can do the following:

    In [103]:
    df.groupby(level=0).diff().fillna(df).reset_index()
    
    Out[103]:
       name        day     no
    0  Jack     Monday   10.0
    1  Jack    Tuesday   30.0
    2  Jack  Wednesday   50.0
    3  Jill     Monday   40.0
    4  Jill  Wednesday  110.0
    

    So groupby the first index level and call diff to calculate the inter row differences per group and fill the NaN values with the original df values and call reset_index

    0 讨论(0)
  • 2021-01-06 01:17

    Here's a method based on zip. It creates two series, the 2nd being offset by 1, and subtracts the difference between the two.

    [n-nn for n,nn in zip(df['No'],df['No'][1:]+[0])]
    
    0 讨论(0)
提交回复
热议问题