Python 中的组合优化

问题描述 投票:0回答:0

我计划与 6 人一起进行高尔夫旅行,尝试优化配对。我从组合的数量开始,然后随机抽样 5 轮。我的目标是创建行 [a,b,c,d,e,f] 与列 [a,b,c,d,e,f] 的交叉矩阵,然后找到使数字最小的分组组合1s.

import pandas
from itertools import permutations, combinations
players = ['a','b','c','d','e','f']
z = pd.DataFrame(combinations(players,3)
for i in z.index:
    players = ['a','b','c','d','e','f']
    players.remove(z.loc[i,0])
    players.remove(z.loc[i,1])
    players.remove(z.loc[i,2])
    z.loc[i,3] = players[0]
    z.loc[i,4] = players[1]
    z.loc[i,5] = players[2] #just to fill out the rest of the matrix

z = 
   0  1  2  3  4  5
0  a  b  c  d  e  f
1  a  b  d  c  e  f
2  a  b  e  c  d  f
3  a  b  f  c  d  e
4  a  c  d  b  e  f
5  a  c  e  b  d  f
6  a  c  f  b  d  e
7  a  d  e  b  c  f
8  a  d  f  b  c  e
9  a  e  f  b  c  d

v = z.sample(5)

opt = pd.DataFrame([], index = ['a','b','c','d','e','f'],columns = ['a','b','c','d','e','f'])
g = pd.concat([v[1].value_counts(),v[2].value_counts()]).sort_index().groupby(level = 0).sum() #pairings count for A
g
Out[116]: 
b    3
c    1
d    1
e    3
f    2

有什么想法/功能可以帮助我吗?我可以在第 1 列和第 2 列中使用 value_counts() 获取第一列,因为第 0 列始终为“a”,但不确定如何填写矩阵的其余部分。 TIA!

解决方案如下所示:

 a    b    c    d    e    f
a  0  0.0  0.0  0.0  0.0  0.0
b  3  0.0  0.0  0.0  0.0  0.0
c  1  0.0  0.0  0.0  0.0  0.0
d  1  0.0  0.0  0.0  0.0  0.0
e  3  0.0  0.0  0.0  0.0  0.0
f  2  0.0  0.0  0.0  0.0  0.0
python pandas combinations
© www.soinside.com 2019 - 2024. All rights reserved.