pandas 按名称对列进行排序 [英] Pandas sort columns by name
问题描述
我有以下数据框,在此我想根据名称对列进行排序.
I have the following dataframe, where I would like to sort the columns according to the name.
1 | 13_1 | 13_10| 13_2 | 2 | 3
9 | 31 | 2 | 1 | 3 | 4
我正在尝试通过以下方式对列进行排序:
I am trying to sort the columns in the following way:
1 | 2 | 3 | 13_1 | 13_2 | 13_10
9 | 3 | 4 | 31 | 1 | 2
我一直在尝试使用df.sort_index(axis=1, inplace=True)
解决此问题,但是结果却与我的初始数据帧相同.即:
I've been trying to solve this using df.sort_index(axis=1, inplace=True)
, however the result turns out to be the same as my initial dataframe. I.e:
1 | 13_1 | 13_10| 13_2 | 2 | 3
9 | 31 | 2 | 1 | 3 | 4
似乎将13_1识别为1.31,而不是13.1.此外,我尝试将列名从字符串转换为浮点型.但是,事实证明这会将13_1和13_10都视为13.1,从而为我提供了重复的列名.
It seems it recognizes 13_1 as 1.31 and not as 13.1. Furthermore, I tried a conversion of the column names from string to float. However, this turns out to treat 13_1 and 13_10 both as 13.1 giving me duplicate column names.
推荐答案
natsort
from natsort import natsorted
df = df.reindex(natsorted(df.columns), axis=1)
# 1 2 3 13_1 13_2 13_10
#0 9 3 4 31 1 2
这篇关于 pandas 按名称对列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!