I have a dataframe that contains years, months and a score. For example:
df = pd.DataFrame({'year' : [2020, 2020, 2021, 2021],
'month': [1, 2, 3, 4],
'score': [10,20,30,40]})
I would like to group by year and every two months. The dataframe after the group by should contain: the year, two months (e.g. 1-2, 3-4, etc) and the mean score.
I've found in other answers that I can map:
months = { '1' : 'B1',
'2' : 'B1',
'3' : 'B2',
'4' : 'B2',
'5' : 'B3',
'6' : 'B3',
'7' : 'B4',
'8' : 'B4',
'9' : 'B5',
'10' : 'B5',
'11' : 'B6',
'12' : 'B6' }
df['two_months'] = df['month'].astype(str).map(months)
And then I can group:
df(['year','two_months'])[['score']].mean()
The problem is that then two_months is a string, and I lose the option to sort it as can be done for datetime objects. My question: is there another way to perform this?