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

如何在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)

输出验证

运行代码后得到的结果与预期完全一致:

ItemRankWeightLocation
01001118loc1
11002221loc2
21003320loc3
3100447loc4
41005527loc7
51006620loc5
61007711loc6
71008831loc8
81009930loc9
910101023loc10

扩展说明

  • 位置数量可通过修改loc_df的生成逻辑灵活调整
  • 禁止分配的位置规则变化时,直接修改forbidden_locs集合即可
  • 逻辑兼容动态物品数量,只要位置总数足够即可正常分配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:15:03