You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何动态重排DataFrame列:元音列优先,其余按字母序排列?

Dynamic Column Reordering: Vowels First, Then Consonants (Sorted Alphabetically)

Great question! Let's work through how to dynamically reorder your DataFrame columns so vowels come first, followed by consonants—with each group sorted alphabetically. No hardcoding column names required, perfect for when you don't know the exact column labels upfront.

First, let's recap your starting DataFrame for context:

import pandas as pd
import numpy as np

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

Which gives us:

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

The Solution: Use a Custom Sort Key

The cleanest way to do this dynamically is to use Python's sorted() function with a custom key that prioritizes vowels first, then sorts alphabetically within each group.

First, define your set of vowels (since we're dealing with uppercase ASCII letters):

vowels = {'A', 'E', 'I', 'O', 'U'}

Then, generate the new column order by sorting the existing columns with a lambda key:

# Sort columns: vowels first (key=0), consonants second (key=1), then alphabetical
new_col_order = sorted(df.columns, key=lambda col: (0 if col in vowels else 1, col))

# Reorder the DataFrame
df_reordered = df[new_col_order]

Result

Running this gives you exactly the desired output:

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

How It Works

The lambda function lambda col: (0 if col in vowels else 1, col) creates a sorting key for each column:

  • The first element of the tuple is 0 if the column is a vowel, 1 otherwise. This ensures all vowels are grouped before consonants (since 0 < 1).
  • The second element is the column name itself, which sorts the columns alphabetically within each group.

Alternative: Split and Combine Columns

If you prefer a more explicit approach, you can split the columns into vowels and consonants, sort each group separately, then combine them:

# Split into vowels and consonants, sort each group
vowel_cols = sorted([col for col in df.columns if col in vowels])
consonant_cols = sorted([col for col in df.columns if col not in vowels])

# Combine and reorder
new_col_order = vowel_cols + consonant_cols
df_reordered = df[new_col_order]

This gives the same result, but the first method with the custom sort key is more concise and efficient.

Both methods work dynamically, so they'll handle any set of single uppercase ASCII column names without needing to hardcode anything.

内容的提问来源于stack exchange,提问作者piRSquared

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:44:30