Reputation: 165
The following code:
import pandas as pd
df_original=pd.DataFrame({\
'race_num':[1,1,1,2,2,2,2,3,3],\
'race_position':[2,3,0,1,0,0,2,3,0],\
'percentage_place':[77,55,88,50,34,56,99,12,75]
})
Gives an output of:
race_num | race_position | percentage_place |
---|---|---|
1 | 2 | 77 |
1 | 3 | 55 |
1 | 0 | 88 |
2 | 1 | 50 |
2 | 0 | 34 |
2 | 0 | 56 |
2 | 2 | 99 |
3 | 3 | 12 |
3 | 0 | 75 |
I need to mainpulate this dataframe to keep the race_num
grouped but sort the percentage place in ascending order - and the race_position
is to stay aligned with the original percentage_place
.
Desired out is:
race_num | race_position | percentage_place |
---|---|---|
1 | 0 | 88 |
1 | 2 | 77 |
1 | 3 | 55 |
2 | 2 | 99 |
2 | 0 | 56 |
2 | 1 | 50 |
2 | 0 | 34 |
3 | 0 | 75 |
3 | 3 | 12 |
My attempt is:
df_new = df_1.groupby(['race_num','race_position'])\['percentage_place'].nlargest().reset_index()
Thank you in advance.
Upvotes: 0
Views: 81
Reputation: 2647
Look into sort_values
In [137]: df_original.sort_values(['race_num', 'percentage_place'], ascending=[True, False])
Out[137]:
race_num race_position percentage_place
2 1 0 88
0 1 2 77
1 1 3 55
6 2 2 99
5 2 0 56
3 2 1 50
4 2 0 34
8 3 0 75
7 3 3 12
Upvotes: 3