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

如何根据pandas DataFrame中指定行的数值对列进行重排序

按指定行数值调整pandas DataFrame列顺序的实现方案

核心逻辑

先保留不需要参与排序的固定列,再提取Model_rank行对应各待排序列的排名值,按升序排序后拼接为最终列顺序即可,所有行数据不会发生变更。

实现代码

场景1:Attributes为普通列(与你给出的结构一致)

import pandas as pd

# 定义不需要参与排序的固定列
fixed_cols = ['index', 'Attributes']
# 提取所有需要按排名排序的业务列
sort_cols = [col for col in df.columns if col not in fixed_cols]

# 提取各业务列对应的Model_rank值,按排名升序排序
sorted_sort_cols = sorted(
    sort_cols,
    key=lambda col: df.loc[df['Attributes'] == 'Model_rank', col].iloc[0]
)

# 拼接最终列顺序并重排DataFrame
final_cols = fixed_cols + sorted_sort_cols
df_result = df[final_cols]

场景2:Attributes已设为行索引

如果后续你把Attributes列设为了行索引,可以用更简洁的写法:

fixed_cols = ['index', 'Attributes']
sort_cols = [col for col in df.columns if col not in fixed_cols]
# 直接按Model_rank行的数值排序列
sorted_sort_cols = df.loc['Model_rank', sort_cols].sort_values().index.tolist()
df_result = df[fixed_cols + sorted_sort_cols]

效果验证

用你提供的测试数据运行后,得到的列顺序为['index', 'Attributes', '1_LR', '2_LR', '3_LR', '4_LR', '1_RFC', '2_RFC'],完全符合预期,所有行的原始数据保持不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:21:02