1. Sort the group
A | B |
a | 1 |
b | 1 |
c | 1 |
b | 2 |
c | 2 |
a | 2 |
b | 3 |
a | 3 |
c | 3 |
Is converted to the following format:
A | B |
a | 1 |
a | 2 |
a | 3 |
b | 1 |
b | 2 |
b | 3 |
c | 1 |
c | 2 |
c | 3 |
code show as below
df_sorted = df.groupby('A',sort=False).apply(lambda x:x.sort_values('B',ascending=True)).reset_index(drop=True)
Minimum and then removed after the two data sets are grouped within
df_head_2 = df_sorted.groupedby('A').head(2)