Issue
I have a pandas dataframe like such:
df = pd.DataFrame({
'class': ['Opn', 'Opn', 'MA', 'CoNo', 'Opn'],
'title': ['Title1', 'Title1', 'Title2', 'Title3', 'Title2'],
'event_count': [16, 11, 8, 7, 5]
})
How can I sort values descending within class and then within title so the output would look like this:
Solution
I made a tmp column similar to what Andrej suggested, but the sum was on the event_count column.
df2 = df.groupby(['class', 'title']).sum()
df3['total_count'] = df2.groupby('class')['event_count'].transform('sum')
df3 = df3.sort_values(by=['class', 'event_count'], ascending=[False, False]).reset_index()
df4 = df3.drop(columns=['total_count'])
Answered By - Peter
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.