Reputation: 387
I have the dataframe below by day, i want to sum group by month . How can i do it please?
date, Revenue, Fourniture
2021-07-01, 200, 5
2021-07-08, 300, 12
2021-08-01, 400, 10
2021-08-18, 200, 12
2021-08-30, 100, 10
2021-08-31, 400, 5
Expected output
2021-07, 500, 17
2021-08, 1400, 47
Upvotes: 1
Views: 1259
Reputation: 23217
You can group by year-month by .groupby()
and take the sum by .sum()
.
As you want the date string as YYYY-mm
in the output, you can use the formatted date string as the Grouper directly. Get the date string by using dt.strftime()
.
# convert to datetime format if not already in datetime
df['date'] = pd.to_datetime(df['date'])
df.groupby(df['date'].dt.strftime('%Y-%m')).sum().reset_index()
Result:
date Revenue Fourniture
0 2021-07 500 17
1 2021-08 1100 37
Upvotes: 2