1

I have a dataframe with column headers "DIV3, DIV4, DIV5 ... DIV30"

My problem is that pandas will sort the columns in the following way:

 DIV10, DIV11, DIV12..., DIV3, DIV4, DIV5

Is there a way to arrange it such that the single digit numbers come first? I.e.:

 DIV3, DIV4, DIV5... DIV30
bdevil
  • 185
  • 1
  • 12

1 Answers1

3

You can solve this by sorting in "human order":

import re
import pandas as pd
def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    def atoi(text):
        return int(text) if text.isdigit() else text

    return [atoi(c) for c in re.split('(\d+)', text)]

columns = ['DIV10', 'DIV11', 'DIV12', 'DIV3', 'DIV4', 'DIV5']    
df = pd.DataFrame([[1]*len(columns)], columns=columns)
print(df)
#    DIV10  DIV11  DIV12  DIV3  DIV4  DIV5
# 0      1      1      1     1     1     1

df = df.reindex(columns=sorted(df.columns, key=natural_keys))
print(df)

yields

   DIV3  DIV4  DIV5  DIV10  DIV11  DIV12
0     1     1     1      1      1      1
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677