我有一个包含列标题为“DIV3,DIV4,DIV5 ... DIV30”的数据框
我的问题是pandas会按以下方式对列进行排序:
DIV10, DIV11, DIV12..., DIV3, DIV4, DIV5
有没有办法安排它使单个数字首先出现?即:
DIV3, DIV4, DIV5... DIV30
答案 0 :(得分: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