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

如何按指定行顺序对Pandas DataFrame列排序并自定义调整列位置?

Pandas按指定行或自定义顺序重排DataFrame列

先看初始数据和结构:

import pandas as pd

data = {'1a': ['C', 3, 1], '2b': ['B', 2, 3], '3c': ['A', 5, 2]}
df = pd.DataFrame(data)

初始输出:

1a 2b 3c
0  C  B  A
1  3  2  5
2  1  3  2

需求1:按指定行的内容顺序排列列

要实现按行0的A、B、C顺序重排列,可提取目标行内容并排序,再获取对应的列名顺序:

# 提取行0的Series,按值排序后取列名
sorted_col_names = df.loc[0].sort_values().index
# 按新顺序重新索引DataFrame
df_sorted = df[sorted_col_names]

运行后输出:

3c 2b 1a
0  A  B  C
1  5  2  3
2  2  3  1

需求2:精细自定义列顺序(如将对应值为"C"的列移至首位)

如果需要自定义值的顺序(比如['C', 'A', 'B']),可以先建立值与列名的映射,再转换为列名顺序:

# 自定义目标值顺序
target_value_order = ['C', 'A', 'B']
# 从行0构建「值→列名」的映射字典
value_to_column = df.loc[0].reset_index().set_index(0)['index'].to_dict()
# 转换为列名顺序
custom_col_order = [value_to_column[val] for val in target_value_order]
# 重排DataFrame
df_custom = df[custom_col_order]

运行后输出:

1a 3c 2b
0  C  A  B
1  3  5  2
2  1  2  3

如果已经明确知道值对应的列名,也可以直接写列名列表(比如['1a', '3c', '2b'])来重排,上面的方法更适合需要动态匹配值和列名的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:58:23