Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to group by month and another column pandas data frame

I have a data frame that looks like below:

import pandas as pd

df = pd.DataFrame({'Date':[2019-08-06,2019-08-08,2019-08-01,2019-10-12], 'Name':['A','A','B','C'], 'grade':[100,90,69,80]})

I want to groupby the data by month and year from the Datetime and also group by Name. Then sum up the other columns.

So, the desired output will be something similar to this

df = pd.DataFrame({'Date':[2019-08, 2019-08, 2019-10-12], 'Name':['A','B','C'], 'grade':[190,69,80]})

I have tried grouper

df.groupby(pd.Grouper(freq='M').sum()

However, it won't take the Name column into play and just drop the entire column.

like image 427
Yun Tae Hwang Avatar asked Oct 22 '25 22:10

Yun Tae Hwang


2 Answers

Try :

df['Date'] = pd.to_datetime(df.Date)
df.groupby([df.Date.dt.to_period('M'), 'Name']).sum().reset_index()

    Date    Name    grade
0   2019-08   A     190
1   2019-08   B     69
2   2019-10   C     80
like image 142
sammywemmy Avatar answered Oct 25 '25 12:10

sammywemmy


I assume date column is of dtype datetime. Then group with

grouped = df.groupby([df.Date.dt.year, df.Date.dt.month, 'Name']).sum()
like image 41
RichieV Avatar answered Oct 25 '25 11:10

RichieV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!