Pandas: sum column values against specific value in another column

Viewed 30

I am using this data frame:

InvoiceNo    Amount    Year-Month
1            100       2019-01
2            125       2019-02
3            200       2019-02
4            300       2019-03
5            120       2019-03
6            350       2019-03
7            500       2019-04
8            230       2019-04
9            100       2019-04
10           200       2019-05

I want to sum up value against all the same months and display new column with those monthly values like this:

InvoiceNo    Amount    Year-Month    MonthlyValue
1            100       2019-01       100
2            125       2019-02       325
3            200       2019-02       325
4            300       2019-03       770
5            120       2019-03       770
6            350       2019-03       770
7            500       2019-04       830
8            230       2019-04       830
9            100       2019-04       830
10           200       2019-05       200

I tried df['MonthlyValue'] = df.groupby(['Year-Month'])['Year-Month'].transform(sum) and it doesn't seem to work.

1 Answers

You are close, need specify column Amount after groupby:

df['MonthlyValue'] = df.groupby('Year-Month')['Amount'].transform('sum')
Related