Alejandro Simkievich
Alejandro Simkievich

Reputation: 3792

pandas DataFrame cumulative value

I have the following pandas dataframe:

>>> df

    Category     Year      Costs
0      A           1       20.00
1      A           2       30.00
2      A           3       40.00
3      B           1       15.00
4      B           2       25.00
5      B           3       35.00

How do I add a cumulative cost column that adds up the cost for the same category and previous years. Example of the extra column with previous df:

>>> new_df

    Category     Year      Costs    Cumulative Costs
0      A           1       20.00         20.00
1      A           2       30.00         50.00
2      A           3       40.00         90.00
3      B           1       15.00         15.00
4      B           2       25.00         40.00
5      B           3       35.00         75.00

Suggestions?

Upvotes: 1

Views: 144

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169494

This works in pandas 0.17.0 Thanks to @DSM in the comments for the terser solution.

df['Cumulative Costs'] = df.groupby(['Category'])['Costs'].cumsum()

>>> df
  Category  Year  Costs  Cumulative Costs
0        A     1     20                20
1        A     2     30                50
2        A     3     40                90
3        B     1     15                15
4        B     2     25                40
5        B     3     35                75

Upvotes: 2

Related Questions