logo

... cvxpy one: more constraints



Notes

This is the new problem definition with constraints;

import cvxpy as cp
import pandas as pd

df = pd.read_csv("/path/to/stigler.csv")
price = df['price_cents'].values

x = cp.Variable(price.shape[0])
objective = cp.Minimize(cp.sum(price*x))
constraints = [
    x >= 0,
    cp.sum(df['vitamin_c_mg'].values * x) >= 75,
    cp.sum(df['iron_mg'].values * x) >= 12,
    cp.sum(df['vitamin_b1_mg'].values * x) >= 1.8,
    cp.sum(df['vitamin_b2_mg'].values * x) >= 2.7,
]
prob = cp.Problem(objective, constraints)
prob.solve()

This is the pandas code at the bottom;

(df
 .assign(assignment = x.value)
 .sort_values(['assignment'], ascending=False)
 .head(5))

Feedback? See an issue? Something unclear? Feel free to mention it here.



If you want to be kept up to date, consider signing up for the newsletter.