Groupby
AnsweredHi everyone!
I hope you are all well.
I am trying to write a constraint for which I need to group by a certain variable but I do not know how to do it with Gurobi.
The problem that I am working on involves knowing whether to supply or not a product for a certain day. Thus, I have a gurobi variable called 'supply', which is binary (1 if True, 0 if False). I also have 200 days in my dataframe, and a "period" column that says to which period a certain day corresponds (for example, the 1st of january corresponds to period 1, the 10th corresponds to period 2, the 13th to period 3 etc..).
Let me give you a concrete example of what the result looks like :
{'1st of January', 'Period 1', 0}
{'2nd of January', 'Period 1', 0}
{'10th of January', 'Period 2', 1}
....
I have created my variable as such :
supply = m.addVars(days,vtype=GRB.BINARY, name = "supply")
Essentially, I have 200 rows at the end (one for each day), and everything is fine so far.
However, my obstacle is that I would like to add a constraint which limits the supply per 'period' to 2.
Basically, I want to group by period, sum the amount, and limit that to 2. Thus, I don't want the number of supplies to be more than 2 for each period.
All in all, my question is : How do I group by with gurobi objects? If I was working with a pandas DataFrame, I would simply have used df.groupby('period').sum('supply') <= 2
Best regards,
Othman
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi Othman,
You can use the tupledict.sum() method to find the sum of the values associated with keys that match the specified pattern. Using your example, the following code snippet shows a minimal example of how to add constraints limiting the total supply per period.
data = {
"day": ["1st of January", "2nd of January", "10th of January"],
"period": [1, 1, 2],
}
df = pandas.DataFrame.from_dict(data)
model = gurobipy.Model("model")
supply = model.addVars(df["day"], vtype=GRB.BINARY, name="supply")
for period in df["period"].unique():
# Select the days associated with each period
days_per_period = df[df["period"] == period]["day"]
model.addConstr(
supply.sum(days_per_period) <= 2,
name=f"supply_limit_per_period_{period}",
)Best regards,
Maliheh
0
Post is closed for comments.
Comments
2 comments