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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.