首页 > 解决方案 > 在前 4 个字符后按字母顺序对 pandas 数据帧进行排序

问题描述

我有一个这样的数据框

    new_col    new_elements       new_val     old_col   old_elements   old_val
 0  0          384444683          593         2         423483819      480
 1  1          384444684          594         32        248239340      341
 2  2          384444686          596         0         249289049      342

我想要这个:

    new_col    old_col   new_elements      old_elements     new_val     old_val   
 0  0          2         384444683         423483819        593         480     
 1  1          32        384444684         248239340        594         341
 2  2          0         384444686         249289049        596         342

我知道这df.sort_index(axis=1)会按字母顺序对我的列进行排序,但它们现在已经按这种方式排序了。我想要的是让它们在前缀之后按字母顺序排序(前 4 个字符)

标签: pythonpython-3.xpandasjupyter

解决方案


col = df.columns
col = sorted(col,key=lambda x: x[4:])
col
df = df[col]
df

在此处输入图像描述

完全放df = df[sorted(df.columns,key=lambda x: x[4:])]


推荐阅读