1

I'm trying to sort col headers by last 3 columns only. Using below, sort_index works on the whole data frame but not when I select the last 3 cols only.

Note: I can't hard-code the sorting because I don't know the columns headers beforehand.

import pandas as pd

df = pd.DataFrame({
    'Z' : [1,1,1,1,1],  
    'B' : ['A','A','A','A','A'],                  
    'C' : ['B','A','A','A','A'], 
    'A' : [5,6,6,5,5],                         
    })

# sorts all cols
df = df.sort_index(axis = 1)

# aim to sort by last 3 cols
#df.iloc[:,1:3] = df.iloc[:,1:3].sort_index(axis=1)

Intended Out:

   Z  A  B  C
0  1  A  B  5
1  1  A  A  6
2  1  A  A  6
3  1  A  A  5
4  1  A  A  5
jonboy
  • 415
  • 4
  • 14
  • 45
  • Does this answer your question? [How to change the order of DataFrame columns?](https://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns). Gives you a couple of options for ways to go about this – noah Nov 18 '20 at 00:51
  • No it doesn't. I've re-arranged the question – jonboy Nov 18 '20 at 01:12

1 Answers1

2

Try with reindex

out = df.reindex(columns=df.columns[[0]].tolist()+sorted(df.columns[1:].tolist()))
Out[66]: 
   Z  A  B  C
0  1  5  A  B
1  1  6  A  A
2  1  6  A  A
3  1  5  A  A
4  1  5  A  A

Method two insert

newdf = df.iloc[:,1:].sort_index(axis=1)
newdf.insert(loc=0, column='Z', value=df.Z)
newdf
Out[74]: 
   Z  A  B  C
0  1  5  A  B
1  1  6  A  A
2  1  6  A  A
3  1  5  A  A
4  1  5  A  A
BENY
  • 317,841
  • 20
  • 164
  • 234