如何在Pandas或Python中按规则基于排名和权重为物品分配位置
Python实现物品位置分配方案
实现思路
- 先将物品表按
Rank升序排序,保证优先级高的物品先分配位置 - 维护一个动态的空闲位置列表,按位置的默认顺序排列
- 逐个给优先级从高到低的物品匹配第一个符合规则的空闲位置,匹配成功后将该位置从空闲列表中移除
代码实现
import pandas as pd # 1. 构造示例数据 # 位置列表,可按需扩展数量 loc_df = pd.DataFrame({ 'Location': [f'loc{i}' for i in range(1, 20)] }) # 物品属性表 item_df = pd.DataFrame({ 'Item': [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010], 'Rank': [1,2,3,4,5,6,7,8,9,10], 'Weight': [18,21,20,7,27,20,11,31,30,23] }) # 2. 核心分配逻辑 # 按Rank升序排序物品,保证高优先级先分配 sorted_items = item_df.sort_values('Rank').reset_index(drop=True) # 初始化空闲位置列表 free_locs = loc_df['Location'].tolist() # 重量超25的物品禁止使用的位置集合 forbidden_locs = {'loc4', 'loc5', 'loc6'} allocated_result = [] for _, item in sorted_items.iterrows(): weight = item['Weight'] # 遍历查找第一个符合规则的空闲位置 for idx, loc in enumerate(free_locs): if weight > 25 and loc in forbidden_locs: continue # 匹配成功分配位置 allocated = item.to_dict() allocated['Location'] = loc allocated_result.append(allocated) # 移除已分配的空闲位置 del free_locs[idx] break # 3. 转换为DataFrame输出结果 result_df = pd.DataFrame(allocated_result) print(result_df)
输出验证
运行代码后得到的结果与预期完全一致:
| Item | Rank | Weight | Location | |
|---|---|---|---|---|
| 0 | 1001 | 1 | 18 | loc1 |
| 1 | 1002 | 2 | 21 | loc2 |
| 2 | 1003 | 3 | 20 | loc3 |
| 3 | 1004 | 4 | 7 | loc4 |
| 4 | 1005 | 5 | 27 | loc7 |
| 5 | 1006 | 6 | 20 | loc5 |
| 6 | 1007 | 7 | 11 | loc6 |
| 7 | 1008 | 8 | 31 | loc8 |
| 8 | 1009 | 9 | 30 | loc9 |
| 9 | 1010 | 10 | 23 | loc10 |
扩展说明
- 位置数量可通过修改
loc_df的生成逻辑灵活调整 - 禁止分配的位置规则变化时,直接修改
forbidden_locs集合即可 - 逻辑兼容动态物品数量,只要位置总数足够即可正常分配
内容的提问来源于stack exchange,提问作者Pri D
相关产品推荐
相关产品推荐

