Вы можете достичь своей цели, сделав столбец меток Категориальный , затем отсортировав по ID и Метка . Посмотрим на практике.
import pandas as pd
df = pd.DataFrame( {'ID': [1,1,1,2,2,3,3], "Label": ["a", "b", "a", "a", "c", "a", "b"],
'Text': ["some text", "other text","data", "words", "more words", "text", "short text"]} )
df
ID Label Text
0 1 a some text
1 1 b other text
2 1 a data
3 2 a words
4 2 c more words
5 3 a text
6 3 b short text
Определите порядок ваших этикеток, выполнив:
to_sort = df.Label.value_counts(ascending = True).index
to_sort
Index(['c', 'b', 'a'], dtype='object')
Затем создайте столбец Метка Категориальный следующим образом:
df.Label = pd.Categorical(df.Label,categories = to_sort, ordered = True)
Наконец, сортировка по ID и Метка :
df.sort_values(["ID", "Label"]).reset_index(drop = True)
ID Label Text
0 1 b other text
1 1 a some text
2 1 a data
3 2 c more words
4 2 a words
5 3 b short text
6 3 a text