我有一个带有列标题“DIV3、DIV4、DIV5 ... DIV30”的数据框
我的问题是 pandas 会按以下方式对列进行排序:
DIV10, DIV11, DIV12..., DIV3, DIV4, DIV5
有没有办法让个位数排在前面?即:
DIV3, DIV4, DIV5... DIV30
最佳答案
您可以通过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
关于python - 对 pandas 数据框中的列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26595546/