Pandas如何在col1总和≤15000约束下最大化选中行的col2总和
实现方案
这个需求本质是0-1背包问题:col1列对应背包问题中的物品重量,约束为总重量≤15000,col2列对应物品价值,目标是总价值最大化。
因为你当前的数据集只有7行,总共有128种可选行组合,直接穷举所有子集是最简单的实现方式,不需要依赖额外的算法库,仅用pandas+Python标准库即可完成:
import pandas as pd from itertools import combinations # 构造你的DataFrame df = pd.DataFrame({ "col1": [1000, 2000, 1500, 3000, 4500, 8500, 6300], "col2": [250, 750, 350, 800, 2500, 4450, 1250] }) weight_limit = 15000 max_total_col2 = 0 best_rows_index = [] # 遍历所有可能的选行数量 for select_n in range(1, len(df)+1): # 遍历对应数量的所有索引组合 for index_group in combinations(df.index, select_n): total_col1 = df.loc[index_group, "col1"].sum() # 满足重量约束再判断价值 if total_col1 <= weight_limit: total_col2 = df.loc[index_group, "col2"].sum() if total_col2 > max_total_col2: max_total_col2 = total_col2 best_rows_index = list(index_group) # 打印结果 print("最优选中行:") print(df.loc[best_rows_index]) print(f"col1总和:{df.loc[best_rows_index, 'col1'].sum()}") print(f"col2最大总和:{max_total_col2}")
运行后输出的最优结果为:
选中索引1、4、5的三行,col1总和刚好为15000,col2总和为7700。
如果后续数据量变大,可以直接使用成熟的整数规划库(如ortools、mip)求解,不需要自己手写动态规划逻辑。
内容的提问来源于stack exchange,提问作者user9996043
相关产品推荐
相关产品推荐

