简体   繁体   中英

Pandas column sort within a group, ignoring other columns

I have to sort a column within a pandas df by a grouped variable id. The sort will not change the order of any other variable, other than it's own (sq3).

My data looks like

index id sq1 sq2 sq3
0   0   0   0   0
1   0   0   1   1
2   0   0   2   2
3   0   0   3   3
4   0   0   5   5
5   0   0   4   4
6   0   0   6   6
7   0   0   7   7
8   0   0   8   8
9   0   0   9   9

And I want to achieve

index id sq1 sq2 sq3
0   0   0   0   0
1   0   0   1   1
2   0   0   2   2
3   0   0   3   3
4   0   0   5   4
5   0   0   4   5
6   0   0   6   6
7   0   0   7   7
8   0   0   8   8
9   0   0   9   9

I have tried the following code that worked, but takes a very long time. Any improvement will be greatly appreciated!

df_groups = df.groupby(['id','sq1'])

for name,group in df_groups:
df_groups.apply(lambda x: x['sq3'].sort_values(ascending=False).values)

transform

df.groupby(['id','sq1']).sq3.transform(sorted)

Demo

df.assign(sq3=df.groupby(['id','sq1']).sq3.transform(sorted))

       id  sq1  sq2  sq3
index                   
0       0    0    0    0
1       0    0    1    1
2       0    0    2    2
3       0    0    3    3
4       0    0    5    4
5       0    0    4    5
6       0    0    6    6
7       0    0    7    7
8       0    0    8    8
9       0    0    9    9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM