alberto
alberto

Reputation: 63

Sum of Previous Rows per Group

I have a dataframe that looks like this.

d = {'name': ["eric", "eric","eric", "sean","sean","sean"], 'values': [1, 5, 7, 4, 2, 5]}
df = pd.DataFrame(data=d)

And I am trying to add a new column called df['sum'] where it adds up the value of the previous row for each unique name in the df['name'] column, so that it would look like this:

name    values    sum
eric    1         1
eric    5         6
eric    4         10
sean    7         7
sean    2         9
sean    5         14

I tried using the below, but can't figure out how to get it to start over each time it gets to a new name.

for i in df['name']:
    df['sum'] = df['values'].cumsum()

Upvotes: 1

Views: 381

Answers (1)

wwnde
wwnde

Reputation: 26686

Use groupby().cumsum()

df.groupby('name').values.cumsum()

Upvotes: 2

Related Questions