gpt4 book ai didi

python - PuLP:每组仅使用一项

转载 作者:行者123 更新时间:2023-12-01 03:42:55 25 4
gpt4 key购买 nike

我有一个具有以下值的 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

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

对我有什么建议吗?

谢谢!

最佳答案

你可以这样做:

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)

关于python - PuLP:每组仅使用一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39274840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com