2014-10-27 312 views
1

我有列標題的數據框「DIV3,DIV4,DIV5 ... DIV30」在大熊貓數據幀排序列

我的問題是,大熊貓將通過以下方式對列進行排序:

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

有沒有辦法來安排它,使得單個數字的數字是第一位的?即:

DIV3, DIV4, DIV5... DIV30 

回答

3

您可以通過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) 

產量

DIV3 DIV4 DIV5 DIV10 DIV11 DIV12 
0  1  1  1  1  1  1