Aniello Guida
Aniello Guida

Reputation: 1

Cumsum Python Dataframe - until previous row

I have a problem. I would replicate this Excel formula:

=SUMIFS($AD$6:AD6;$D$6:D6;D7)

I want obtain a cumulative result until previous row

ID = [1,1,1,2,2]
$ = [10,10,10,10,10]

Result = [nan,10,20,nan,10]

thanks

Upvotes: 0

Views: 129

Answers (1)

jezrael
jezrael

Reputation: 862671

Use lambda function with Series.shift and Series.cumsum in GroupBy.transform or GroupBy.apply:

df = pd.DataFrame({
    'ID':[1,1,1,2,2],
    '$': [10,10,10,10,10]
    })

df['new'] = df.groupby('ID')['$'].transform(lambda x: x.shift().cumsum())
#alternative
#df['new'] = df.groupby('ID')['$'].apply(lambda x: x.shift().cumsum())
print (df)
   ID   $   new
0   1  10   NaN
1   1  10  10.0
2   1  10  20.0
3   2  10   NaN
4   2  10  10.0

Upvotes: 1

Related Questions