我有一个用pandas组成的数据框,如下所示:
a b c d e f g h i j k l m n o
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 1 0 1 0 1 0 0 1 0
3 0 1 0 0 1 0 1 0 1 0 1 0 0 1 0
4 0 0 0 0 0 1 0 1 0 0 1 0 0 1 0
5 0 0 1 1 0 1 0 1 0 0 1 0 0 1 0
6 1 0 0 1 0 1 0 1 0 0 1 0 0 1 0
7 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
8 0 0 0 0 0 0 0 0 1 0 1 0 0 1 0
9 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0
10 0 0 0 1 0 1 0 1 0 0 1 0 0 1 0
11 0 0 0 0 0 0 0 1 0 0 1 0 0 1 0
12 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0
13 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0
14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
15 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0
16 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
我想对行进行排序,以便按降序排序。行的值是通过组合列形成的数字。例如,第1行是000000000000000,第2行是000000101010010.最终结果应该将第6行作为第一行,将第1行作为最后一行。我试过了
dat.sort_values(by=['a'], ascending=False, axis=0)
但这仅在第一列中排序。还有其他方法可以重新排序行吗?
答案 0 :(得分:4)
按当前顺序排列所有列:
df.sort_values(by=df.columns.tolist(), ascending=False)
# a b c d e f g h i j k l m n o
#6 1 0 0 1 0 1 0 1 0 0 1 0 0 1 0
#3 0 1 0 0 1 0 1 0 1 0 1 0 0 1 0
#5 0 0 1 1 0 1 0 1 0 0 1 0 0 1 0
#10 0 0 0 1 0 1 0 1 0 0 1 0 0 1 0
#12 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0
#15 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0
#4 0 0 0 0 0 1 0 1 0 0 1 0 0 1 0
#2 0 0 0 0 0 0 1 0 1 0 1 0 0 1 0
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