列ヘッダーが「DIV3、DIV4、DIV5 ... DIV30」のデータフレームがあります。
私の問題は、パンダが次のように列を並べ替えることです。
DIV10, DIV11, DIV12..., DIV3, DIV4, DIV5
1桁の数字が最初になるように配置する方法はありますか?すなわち:
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加