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

如何按列名末尾字符重新排序DataFrame列?含具体列名示例

高效重排DataFrame列名的方法

假设你使用的是pandas库,这里提供两种高效的实现方式,适配你的列名规律(前缀+下划线+后缀)完成排序需求:

方法一:利用排序键直接排序

代码简洁直观,适合列名规则固定的场景:

import pandas as pd

# 假设你的DataFrame为df
cols = df.columns.tolist()

# 指定前缀的优先级顺序
prefix_priority = {'EoT': 0, 'PR': 1, 'PD': 2, 'CR': 3}
# 单独提取SUBJID列
subjid_col = 'SUBJID'
other_cols = [col for col in cols if col != subjid_col]

# 先按后缀(A/B/C/D)排序,后缀相同时按指定前缀顺序排序
sorted_other_cols = sorted(other_cols, key=lambda x: (x.split('_')[1], prefix_priority[x.split('_')[0]]))

# 组合新列顺序并重新排列DataFrame
new_col_order = [subjid_col] + sorted_other_cols
df = df[new_col_order]

方法二:利用分类变量(Categorical)排序

如果后续需要扩展前缀/后缀顺序,或担心字符串拆分出错,用分类变量的方式更严谨:

import pandas as pd

cols = df.columns.tolist()
subjid_col = 'SUBJID'
other_cols = [col for col in cols if col != subjid_col]

# 定义前缀和后缀的固定顺序
prefix_order = pd.Categorical(['EoT', 'PR', 'PD', 'CR'], ordered=True)
suffix_order = pd.Categorical(['A', 'B', 'C', 'D'], ordered=True)

# 将列名拆分为前缀和后缀,转为分类类型后排序
cols_df = pd.DataFrame({'col_name': other_cols})
cols_df[['prefix', 'suffix']] = cols_df['col_name'].str.split('_', expand=True)
cols_df['prefix'] = pd.Categorical(cols_df['prefix'], categories=prefix_order, ordered=True)
cols_df['suffix'] = pd.Categorical(cols_df['suffix'], categories=suffix_order, ordered=True)

# 按后缀、前缀排序后提取列名
cols_df_sorted = cols_df.sort_values(by=['suffix', 'prefix'])
sorted_other_cols = cols_df_sorted['col_name'].tolist()

# 重排DataFrame
new_col_order = [subjid_col] + sorted_other_cols
df = df[new_col_order]

两种方法的时间复杂度均为O(n log n)(n为列数),对于常规规模的DataFrame来说效率完全足够。执行后,列名将按照SUBJID → EoT_A/PR_A/PD_A/CR_A → EoT_B/PR_B/PD_B/CR_B的目标顺序排列。

内容的提问来源于stack exchange,提问作者D. Shin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:20:41