I have the following dataframe:
Week Total
1 5
2 6
3 10
I want to make Week 2 equal to week1 week2, Week 3 equal to week1 week 2 week 3. My dataframe is bigger than this so simply doing additions doesn't work as the number of weeks can change dynamically. I honestly have no clue how to approach this. I was thinking maybe doing a for loop that iterates every week and subtracts the lowest week number from current to know how many weeks it needs to add. But it doesn't sound like a clean approach. Is there a better solution?
CodePudding user response:
Use a cumsum
after sorting the rows by Week (if needed):
out = (df
.sort_values('Week')
.assign(Total=lambda d: d['Total'].cumsum())
)
If the weeks are already sorted:
df['Total'] = df['Total'].cumsum()
output:
Week Total
0 1 5
1 2 11
2 3 21