[英]Pandas column sort within a group, ignoring other columns
我必須按分組變量 id 對 pandas df 中的列進行排序。 排序不會改變任何其他變量的順序,除了它自己的 (sq3)。
我的數據看起來像
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
我想實現
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
我嘗試了以下有效的代碼,但需要很長時間。 任何改進將不勝感激!
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)
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.