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

如何在Python中对DataFrame多列排序并指定某列自定义映射规则?

解决方案

要同时实现按Code、Item常规排序,以及Type列的自定义顺序排序,你可以用以下两种基于Pandas的sort_values方法实现:

方法一:将Type列转为分类类型(推荐,后续操作可沿用自定义顺序)

  1. 定义Type的自定义排序顺序
  2. 将Type列转换为有序分类类型,指定目标顺序
  3. 调用sort_values,按Code、Item、Type的优先级排序

示例代码:

import pandas as pd

# 构造匹配场景的示例数据(每组Code+Item至少4条数据)
df = pd.DataFrame({
    'Code': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
    'Item': ['X', 'X', 'X', 'X', 'Y', 'Y', 'Y', 'Y'],
    'Type': ['Customer', 'Admin', 'User', 'Staff', 'Staff', 'Customer', 'Admin', 'User'],
    'OtherCol': [1, 2, 3, 4, 5, 6, 7, 8]
})

# 1. 定义Type的自定义排序映射
type_custom_order = ['Admin', 'Staff', 'User', 'Customer']

# 2. 把Type列转为有序分类
df['Type'] = pd.Categorical(df['Type'], categories=type_custom_order, ordered=True)

# 3. 多列排序
sorted_df = df.sort_values(by=['Code', 'Item', 'Type'])

print(sorted_df)

输出结果中,每个Code+Item组内的Type会严格按照Admin → Staff → User → Customer的顺序排列。

方法二:使用sort_values的key参数(不修改原列类型,仅排序时生效)

如果不想改变原DataFrame中Type列的类型,可以用key参数临时映射排序权重:

import pandas as pd

# 沿用上述示例df
type_order_map = {'Admin': 0, 'Staff': 1, 'User': 2, 'Customer': 3}

# 排序时给Type列映射权重,按权重大小排序
sorted_df = df.sort_values(
    by=['Code', 'Item', 'Type'],
    key=lambda col: col.map(type_order_map) if col.name == 'Type' else col
)

print(sorted_df)

这个方法通过给每个Type值分配数字权重,排序时按权重大小排列,同样能达到目标效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:22:38