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

如何自定义排序DataFrame?按多列分组并按指定区域归类排序

问题描述

现有如下示例DataFrame:

NameStateLocation
JamieNew YorkManhattan
MaryOhioDowntown Cleveland
JohnNew YorkFlushing Queens
SamOhioLakewood Cleveland
JamesOhioBeachwood Cleveland
PerryNew YorkUptown Manhattan
DianeNew YorkBriarwood Queens
JulieNew YorkLower Manhattan

需求:对该DataFrame按State和自定义分组的Location排序,规则如下:

  • 将Location中包含Manhattan的记录归为一组,包含Queens的归为一组,包含Cleveland的归为一组
  • 自定义分组的排序顺序为 [Manhattan, Queens, Cleveland]
  • 最终期望得到如下排序结果:
NameStateLocation
JamieNew YorkManhattan
PerryNew YorkUptown Manhattan
JulieNew YorkLower Manhattan
JohnNew YorkFlushing Queens
DianeNew YorkBriarwood Queens
MaryOhioDowntown Cleveland
SamOhioLakewood Cleveland
JamesOhioBeachwood Cleveland

此前尝试过需要枚举所有Location取值的排序方案,现寻求无需枚举所有值的最优实现方法。

最优实现方法

可以通过构造自定义排序键的方式实现,无需枚举所有Location取值,步骤如下:

步骤1:初始化数据与分组规则

import pandas as pd

# 定义自定义分组的优先级顺序
group_order = ["Manhattan", "Queens", "Cleveland"]

# 原始DataFrame
df = pd.DataFrame({
    "Name": ["Jamie", "Mary", "John", "Sam", "James", "Perry", "Diane", "Julie"],
    "State": ["New York", "Ohio", "New York", "Ohio", "Ohio", "New York", "New York", "New York"],
    "Location": ["Manhattan", "Downtown Cleveland", "Flushing Queens", "Lakewood Cleveland", "Beachwood Cleveland", "Uptown Manhattan", "Briarwood Queens", "Lower Manhattan"]
})

步骤2:生成排序键列

通过apply遍历Location列,匹配对应的分组并返回其在优先级列表中的索引,作为排序依据:

# 生成排序键:匹配到分组则返回对应索引,未匹配到默认放最后
df["sort_key"] = df["Location"].apply(
    lambda x: next((i for i, group in enumerate(group_order) if group in x), len(group_order))
)

步骤3:执行排序并清理临时列

先按State排序,再按sort_key(自定义分组优先级)排序,最后删除临时的sort_key列:

# 排序:可根据需求在同一分组内添加Location排序(可选)
sorted_df = df.sort_values(by=["State", "sort_key", "Location"]).drop(columns="sort_key")

# 输出结果
print(sorted_df)

方案说明

  • 仅需维护group_order列表即可调整分组顺序,无需枚举所有Location取值
  • next(..., len(group_order))确保未匹配到目标分组的记录会被放到所有指定分组之后
  • 若需要在同一分组内进一步排序,可在sort_values的by参数中添加对应列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:06:18