Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas dataframe sort columns according to column totals

I was able to sort rows according to the last column. However, I also have a row at the bottom of the dataframe which has the totals of each column. I couldn't find a way to sort the columns according to the totals in the last row. The table looks like the following:

   A  B  C  T
0  9  9  9  27
1  9  10 4  23
2  7  4  8  19
3  2  6  9  17
T  27 29 30

I want this table to be sorted so that the order of columns will be from left to right C, B, A from highest total to lowest. How can this be done?

like image 894
nealous3 Avatar asked Nov 20 '25 23:11

nealous3


1 Answers

Use DataFrame.sort_values by index value T with axis=1:

df = df.sort_values('T', axis=1, ascending=False)
print (df)
    C   B   A     T
0   9   9   9  27.0
1   4  10   9  23.0
2   8   4   7  19.0
3   9   6   2  17.0
T  30  29  27   NaN
like image 88
jezrael Avatar answered Nov 22 '25 14:11

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!