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

如何基于字符串层级对pandas dataframe分组并提取各客户最高优先级

实现方法

先把Priority字段设置为符合优先级规则的有序分类类型,让pandas可以识别Low<Medium<High的大小逻辑,之后分组取最大值即可,代码如下:

import pandas as pd

# 构造示例数据,已有数据可以跳过这步
df = pd.DataFrame({
    'Client': ['Client 1', 'Client 1', 'Client 2', 'Client 2', 'Client 3'],
    'Priority': ['Low', 'Medium', 'Low', 'High', 'Low']
})

# 定义优先级顺序,转换为有序分类类型
priority_order = ['Low', 'Medium', 'High']
df['Priority'] = pd.Categorical(df['Priority'], categories=priority_order, ordered=True)

# 按客户分组取最高优先级
res = df.groupby('Client', as_index=False)['Priority'].max()

运行后得到的res就是你需要的结果:

ClientPriority
Client 1Medium
Client 2High
Client 3Low

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:15:10