lundi 11 juillet 2016

Rearrange the columns of a pandas DataFrame so that the column with highest total is first


I have this DataFrame:

df = pd.DataFrame({'c1':[1,2,3,4]
                       ,'c2':[2,4,5,6]
                       ,'c3':[5,7,9,10]
                       ,'c4':[-1,3,1,0]
                       ,'c5':[100,1000,1,2]})
df

    c1  c2  c3  c4  c5
0   1   2   5   -1  100
1   2   4   7   3   1000
2   3   5   9   1   1
3   4   6   10  0   2

What I don't know how to do is quickly sort the columns so the column with the highest total c5 comes first, then c3, c2, c1 and c4:

    c1  c2  c3  c4  c5
0   1   2   5   -1  100
1   2   4   7   3   1000
2   3   5   9   1   1
3   4   6   10  0   2

So is there a command to produce the following result (without hard-coding the column names)?

df[['c5', 'c3', 'c2', 'c1' , 'c4']]

    c5  c3  c2  c1  c4
0   100     5   2   1   -1
1   1000    7   4   2   3
2   1   9   5   3   1
3   2   10  6   4   0

Aucun commentaire:

Enregistrer un commentaire