python - 按单个字符名称对列进行排序,元音在前

标签 python pandas sorting

考虑数据框 df

df = pd.DataFrame(np.arange(25).reshape(5, 5), columns=list('CBESA'))
df

    C   B   E   S   A
0   0   1   2   3   4
1   5   6   7   8   9
2  10  11  12  13  14
3  15  16  17  18  19
4  20  21  22  23  24

我想重新排列列,使元音位于辅音之前,否则按字母顺序排列。

我可以使用 sort_index 按字母顺序对列进行排序

df.sort_index(1)

    A   B   C   E   S
0   4   1   0   2   3
1   9   6   5   7   8
2  14  11  10  12  13
3  19  16  15  17  18
4  24  21  20  22  23

但这会使 'E' 乱序。
我可以“手动”得到我想要的东西

df[list('AEBCS')]

    A   E   B   C   S
0   4   2   1   0   3
1   9   7   6   5   8
2  14  12  11  10  13
3  19  17  16  15  18
4  24  22  21  20  23

考虑到我不知道确切的字母,我该如何动态地执行此操作?我知道它们是单字符 ascii 大写字母。

最佳答案

你需要sorted + reindex

df.reindex(columns=[
    x[1] for x in sorted(zip(~df.columns.isin(list('AEIOU')), df.columns))
])
如果您将使用 zip 生成的元组列表/容器传递给它,

sorted 将对多个谓词进行排序。

或者,采纳 piR 的建议并使用 lambda 进行排序:

df.reindex(
    columns=sorted(df.columns, key=lambda x: (x not in 'AEIOU', x))
)

    A   E   B   C   S
0   4   2   1   0   3
1   9   7   6   5   8
2  14  12  11  10  13
3  19  17  16  15  18
4  24  22  21  20  23

关于python - 按单个字符名称对列进行排序,元音在前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49442780/

相关文章:

python - 有哪些学习 pycURL 的好教程?

python - 使用 Pandas 根据另一列的值选择一列

python - 如何在不复制列的情况下合并 Pandas 数据框

javascript - 如何对 View (IEnumerable) 中的列表进行排序并保持过滤?

jquery - 排序(按字母顺序)以忽略空单元格 : dataTables

python - python中的子进程不产生输出

python - 如何运行在多核上使用 numpy 的 python 程序,最好使用线程

python - 二维 numpy 数组搜索(相当于 Matlab 的 intersect 'rows' 选项)

python - 如果 Pandas 小于该值,则将列中的值设置为等于 5% 分位数

c# - 根据类中的值从最小到最大排序