Search code examples
pythonpandasdataframecumsum

Pandas cumsum with growth rate


I want to calculate the cumsum but also add a growth rate to each sum.

Growth rate = 0.1

Each row for the Cumsum with Growth column will add a growth component from the previous rows cumsum:
Row 2 = (1+2) + (1*0.1)
Row 3 = (3.1 + 1) + (3.1 * 0.1)
Row 4 = (4.41 + 5) + (4.41* 0.1)

How can I accomplish this without iterating each row in Pandas?


Solution

  • You might try this :

    col = [df.val.values[0]]
    for i in range(1, len(df.index)):
        col.append(col[i-1]+df.val.values[i]+col[i-1]*0.1)
    df['cumsumwithgrowth'] = col
    

    df

       val  cumsumwithgrowth
    0    1             1.000
    1    2             3.100
    2    1             4.410
    3    5             9.851