简体   繁体   中英

Sorting columns in pandas dataframe

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? Ie:

 DIV3, DIV4, DIV5... DIV30

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM