[英]Sorting columns in pandas dataframe
我有一個帶有列標題“DIV3,DIV4,DIV5 ... DIV30”的數據框
我的問題是pandas會按以下方式對列進行排序:
DIV10, DIV11, DIV12..., DIV3, DIV4, DIV5
有沒有辦法安排它,以便單個數字首先出現? 即:
DIV3, DIV4, DIV5... DIV30
你可以通過“人類秩序”排序來解決這個問題:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.