0

Hi i have panda data frame. I wana sort data with respect of a group id and sorting with respect of order

id    title      order
2      A           2
2      B           1
2      C           3
3      H           2
3      T           1

out put:

id    title      order
2      B           1
2      A           2
2      C           3
3      T           1
3      H           2
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880

1 Answers1

2

Since you're not aggregating, you can sort by multiple columns to get the output you want.

import pandas as pd

df = pd.DataFrame({'id': [2, 2, 2, 3, 3],
                   'title': ['A', 'B', 'C', 'H', 'T'],
                   'order': [2, 1, 3, 2, 1]})
df = df.sort_values(by=['id', 'order'])
print(df)

Output:

   id title  order
1   2     B      1
0   2     A      2
2   2     C      3
4   3     T      1
3   3     H      2
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880