如何从itertools.combinations创建一个numpy数组而不循环

时间:2017-04-13 01:40:08

标签: python numpy indexing

有没有办法在没有循环的情况下获得此结果?我曾尝试用W[range(W.shape[0]),进行花哨的索引...但到目前为止还没有成功。

import itertools
import numpy as np
n = 4
ct = 2
one_index_tuples = list(itertools.combinations(range(n), r=ct))
W = np.zeros((len(one_index_tuples), n), dtype='int')
for row_index, col_index in enumerate(one_index_tuples):
    W[row_index, col_index] = 1
print(W)

结果:

[[1 1 0 0]
 [1 0 1 0]
 [1 0 0 1]
 [0 1 1 0]
 [0 1 0 1]
 [0 0 1 1]]

2 个答案:

答案 0 :(得分:2)

您可以使用花式索引(advanced indexing),如下所示:

# reshape the row index to 2d since your column index is also 2d so that the row index and 
# column index will broadcast properly
W[np.arange(len(one_index_tuples))[:, None], one_index_tuples] = 1

W
#array([[1, 1, 0, 0],
#       [1, 0, 1, 0],
#       [1, 0, 0, 1],
#       [0, 1, 1, 0],
#       [0, 1, 0, 1],
#       [0, 0, 1, 1]])

答案 1 :(得分:0)

试试这个:

[[ 1 if i in x else 0 for i in range(n) ] for x in itertools.combinations( range(n), ct )]