python – 比较numpy数组中的多个列

我有一个2D numpy数组,大约12列和1000行,每个单元格包含1到5的数字.我正在根据我的点系统搜索列的最佳六元组,其中1和2生成-1点和4 5给出1.

如果某个六元组中的某行包含例如[1,4,5,3,4,3],则该行的点应为2,因为3 * 1 1 *( – 1)= 2.是[1,2,3,3,3],应该是-3分.

起初,我尝试了一个strait前向循环解决方案,但我意识到有665 280个可能的列组合进行比较,当我还需要搜索最好的五元组,四元组等时,循环将永远占用.

是否有一种更智能的numpy方式来解决我的问题?

最佳答案

import numpy as np
import itertools

N_rows = 10
arr = np.random.random_integers(5, size=(N_rows,12))
x = np.array([0,-1,-1,0,1,1])
y = x[arr]

print(y)

score, best_sextuple = max((y[:,cols].sum(), cols)
                           for cols in itertools.combinations(range(12),6))
print('''\
score: {s}
sextuple: {c}
'''.format(s = score, c = best_sextuple))

收益率,例如,

score: 6
sextuple: (0, 1, 5, 8, 10, 11)

说明:

首先,让我们生成一个随机示例,包含12列和10行:

N_rows = 10
arr = np.random.random_integers(5, size=(N_rows,12))

现在我们可以使用numpy索引将arr 1,2,…,5中的数字转换为值-1,0,1(根据您的评分系统):

x = np.array([0,-1,-1,0,1,1])
y = x[arr]

接下来,让我们使用itertools.combinations生成6列的所有可能组合:

for cols in itertools.combinations(range(12),6)

y[:,cols].sum()

然后给出cols的分数,列的选择(sextuple).

最后,使用max来挑选最高分的六元组:

score, best_sextuple = max((y[:,cols].sum(), cols)
                           for cols in itertools.combinations(range(12),6))
点赞