how to group by month and another column pandas data frame

Viewed 720

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.

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

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

grouped = df.groupby([df.Date.dt.year, df.Date.dt.month, 'Name']).sum()
Related