FMKU
FMKU

Reputation: 1

Sorting the Columns based on value

I had DataFrame with many of columns, I want to sort the the columns based on its total value, in other words the first columns will be with the highest value so

            A   B   C   D   E      F     G  L
Date                                
2010-01-01  0   10  0   0   950     0   40  0
2010-03-01  0   0   0   0   1040    0   0   0
2010-04-01  0   0   0   0   261     0   0   0
2010-05-01  40  10  0   0   207     0   0   300
2010-06-01  0   0   0   0   108     0   0   0
2010-07-01  0   0   0   13  137     0   50  0
2010-08-01  0   10  10  0   0       0   0   0
2010-10-01  0   0   0   0   97      40  40  0

Upvotes: 0

Views: 54

Answers (1)

DSM
DSM

Reputation: 353059

If I'm understanding what you want (example output is always a good idea), one way would be to sum the columns, sort the resulting series, and use that to index into the frame:

>>> colsum = df.sum()
>>> colsum.sort(ascending=False)
>>> df.loc[:, colsum.index]
               E    L   G   F   A   B   D   C
Date                                         
2010-01-01   950    0  40   0   0  10   0   0
2010-03-01  1040    0   0   0   0   0   0   0
2010-04-01   261    0   0   0   0   0   0   0
2010-05-01   207  300   0   0  40  10   0   0
2010-06-01   108    0   0   0   0   0   0   0
2010-07-01   137    0  50   0   0   0  13   0
2010-08-01     0    0   0   0   0  10   0  10
2010-10-01    97    0  40  40   0   0   0   0

Upvotes: 2

Related Questions