按列对数据框中的某些行进行排序

``````Index   Denomination    A   B   C   D
0        100            5   0   0   0
1        100            0   0   1   0
2        100            0   2   0   0
3        200            5   2   0   0
4        200            5   0   1   0
5        200            0   4   0   0
6        200            10  0   0   0
7        200            0   2   1   0
8        200            0   0   2   0
``````

``````Index   Denomination    A   B   C   D
0        100            5   0   0   0
2        100            0   2   0   0
1        100            0   0   1   0
6        200            10  0   0   0
3        200            5   2   0   0
4        200            5   0   1   0
5        200            0   4   0   0
7        200            0   2   1   0
8        200            0   0   2   0
``````

``````df.sort_values(by=['Denomination', 'A', 'B', 'C', 'D'],
ascending=[True, False, False, False, False])
Out:
Denomination   A  B  C  D
0           100   5  0  0  0
2           100   0  2  0  0
1           100   0  0  1  0
6           200  10  0  0  0
3           200   5  2  0  0
4           200   5  0  1  0
5           200   0  4  0  0
7           200   0  2  1  0
8           200   0  0  2  0
``````

`Denomination`升序排序；如果是平局，则按`A`降序排序；如果是平局，则按`B`降序排序，依此类推。

``````df.groupby('Denomination')['Denomination'].transform(pd.Series.first_valid_index)
Out:
0    0
1    0
2    0
3    3
4    3
5    3
6    3
7    3
8    3
Name: Denomination, dtype: int64
``````

``````(df.assign(denomination_group =
df.groupby('Denomination')['Denomination'].transform(pd.Series.first_valid_index))
.sort_values(by=['denomination_group', 'A', 'B', 'C', 'D'],
ascending=[True, False, False, False, False])
.drop('denomination_group', axis=1))
``````

0 条评论