【问题标题】:PuLP: Using only one item per group纸浆:每组仅使用一项
【发布时间】:2016-09-01 14:54:13
【问题描述】:

我有一个具有以下值的 Pandas 数据框:

     Name    Age    City    Points
1    John    24     CHI     35
2    Mary    18     NY      25
.
.
80   Steve   30     CHI     32

我正在尝试组建一个 5 人小组,以最大限度地提高积分总和。我想有两个限制:年龄和城市。最高年龄必须在 110 岁以下,并且不能有两个人来自同一个城市。

目前我有一个脚本可以最大化分数并考虑年龄限制:

x = pulp.LpVariable.dicts("x", df.index, cat='Integer', lowBound=0)
mod = pulp.LpProblem("prog", pulp.LpMaximize)

objvals_p = {idx: (df['Points'][idx]) for idx in df.index}
mod += sum([x[idx]*objvals_p[idx] for idx in df.index])

objvals_a = {idx: (df['Age'][idx]) for idx in df.index}
mod += pulp.lpSum([x[idx]*objvals_a[idx] for idx in df.index]) < 110

但是我不知道如何将城市限制添加到我的脚本中。

对我有什么建议吗?

谢谢!

【问题讨论】:

    标签: python pandas constraints solver pulp


    【解决方案1】:

    你可以这样做:

    for city in df['City'].unique():
        sub_idx = df[df['City']==city].index
        mod += pulp.lpSum([x[idx] for idx in sub_idx]) <= 1
    

    对于 DataFrame 中的每个城市,此总和超过 DataFrame 的一个子集(由 sub_idx 索引),此总和应小于或等于 1,因为来自同一城市的 2 人不能在团队中。

    要使这个(和您的其他约束)起作用,您需要更改决策变量的定义。它应该是二进制的;完整性不够。

    x = pulp.LpVariable.dicts("x", df.index, 0, 1, pulp.LpInteger)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多