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

如何用Pandas将账户均匀分配给客户经理(同账户需归属同一经理)

解决Pandas中同账号批量分配客户经理的问题

问题描述

现有两个Pandas DataFrame:

  • df_am:记录客户经理ID(account_manager_id)及已分配账户总数(account_total)
  • df_poc:记录待分配账户的联系人(point_of_contact)与账号(account_no),同一account_no必须分配给同一个客户经理

需求规则:

  • 遍历df_poc中的所有唯一account_no
  • 每次将账号分配给当前account_total最小的客户经理(若存在多个最小值,选择第一个出现的)
  • 该账号下的所有联系人统一归属此客户经理
  • 分配完成后更新df_am中对应经理的account_total(每个唯一账号计为1个分配账户)

用户此前使用iterrows结合min的方法,无法处理同账号多联系人的情况,导致同一账号被拆分给不同经理,现需要正确实现方案。

输入示例

df_am 初始数据

import pandas as pd

df_am = pd.DataFrame({
    'account_manager_id': [1, 2, 3, 4, 5, 6],
    'account_total': [8, 3, 3, 1, 7, 2]
})

df_poc 初始数据

df_poc = pd.DataFrame({
    'point_of_contact': ['John', 'Bob', 'Sally', 'Greg', 'Bret', 'Corey', 'Chad', 'Mavis', 'Andre', 'Hunter', 'Debra'],
    'account_no': [100, 78, 125, 128, 78, 100, 100, 8, 632, 157, 12]
})

解决方案代码

# 获取所有待分配的唯一账号
unique_accounts = df_poc['account_no'].unique()

# 初始化df_poc的客户经理列
df_poc['account_manager_id'] = None

# 遍历每个唯一账号进行分配
for account in unique_accounts:
    # 找到当前账户总数最小的第一个客户经理
    min_row_idx = df_am['account_total'].idxmin()
    assigned_manager = df_am.loc[min_row_idx, 'account_manager_id']
    
    # 给当前账号的所有联系人分配该经理
    df_poc.loc[df_poc['account_no'] == account, 'account_manager_id'] = assigned_manager
    
    # 更新对应经理的账户总数
    df_am.loc[min_row_idx, 'account_total'] += 1

# 查看结果
print("更新后的df_am:")
print(df_am)
print("\n更新后的df_poc:")
print(df_poc)

输出验证

更新后的df_am

account_manager_id  account_total
0                   1              8
1                   2              5
2                   3              5
3                   4              5
4                   5              7
5                   6              5

更新后的df_poc

point_of_contact  account_no  account_manager_id
0              John         100                   4
1               Bob          78                   6
2             Sally         125                   2
3              Greg         128                   3
4              Bret          78                   6
5             Corey         100                   4
6              Chad         100                   4
7             Mavis           8                   2
8             Andre         632                   3
9            Hunter         157                   4
10             Debra          12                   6

说明

  • 该方案通过先提取唯一账号,确保每个账号只分配一次,避免了同账号拆分的问题
  • 使用idxmin()直接定位最小账户总数的客户经理,比循环遍历更高效
  • 每次分配后即时更新df_am的账户总数,保证后续分配的准确性

内容的提问来源于stack exchange,提问作者a.WOL7

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:48:24