Search code examples
pythonpandaspandas-groupbyranking

Pandas group by and sorting by values within the group


After running XGBoost and getting the prediction, I need to sort the ranks withing the based on group id. I've tried several methods but was unsuccessful.

My data:

id     hotel_id   rank
1       5         2
1       3         3
1       4         1
2       23        4
2       12        2
2       62        3
2       22        1

This would be the outcome after group_by and sorting based on rank. It's important that the id remains unchanged.

id     hotel_id   rank
1       4         1
1       5         2
1       3         3
2       22        1
2       12        2
2       62        3
2       23        4

Solution

  • I believe this is just sort_values:

    df.sort_values(['id','rank'])
    

    Output:

       id  hotel_id  rank
    2   1         4     1
    0   1         5     2
    1   1         3     3
    6   2        22     1
    4   2        12     2
    5   2        62     3
    3   2        23     4