Home > Enterprise >  sort pivot/dataframe without All row pandas/python
sort pivot/dataframe without All row pandas/python

Time:08-08

I created a dataframe with the help of a pivot, and I have:

name      x    y    z    All   
A        155  202  218   575
C        206  149   45   400                   
B        368  215  275   858
Total    729  566  538   1833

I would like sort by column "All" not taking into account row "Total". i am using:

df.sort_values(by = ["All"], ascending = False)

Thank you in advance!

CodePudding user response:

If the Total row is the last one, you can sort other rows and then concat the last row:

df = pd.concat([df.iloc[:-1, :].sort_values(by="All"), df.iloc[-1:, :]])
print(df)

Prints:

name     x    y    z   All
C      206  149   45   400
A      155  202  218   575
B      368  215  275   858
Total  729  566  538  1833

CodePudding user response:

You can try with the following, although it has a FutureWarning you should be careful of:

df = df.iloc[:-1,:].sort_values('All',ascending=False).append(df.iloc[-1,:])

This outputs:

    name    x    y    z   All
2      B  368  215  275   858
0      A  155  202  218   575
1      C  206  149   45   400
3  Total  729  566  538  1833

CodePudding user response:

You can get the sorted order without Total (assuming here the last row), then index by position:

import numpy as np
idx = np.argsort(df['All'].iloc[:-1])

df2 = df.iloc[np.r_[idx[::-1], len(df)-1]]

NB. as we are sorting only an indexer here this should be very fast

output:

    name    x    y    z   All
2      B  368  215  275   858
0      A  155  202  218   575
1      C  206  149   45   400
3  Total  729  566  538  1833

CodePudding user response:

you can just ignore the last column

df.iloc[:-1].sort_values(by = ["All"], ascending = False)
  • Related