2

Is there a way to get this result without a loop? I've made a couple attempts at fancy indexing with W[range(W.shape[0]),... but have been so far unsuccessful.

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)

Result:

[[1 1 0 0]
 [1 0 1 0]
 [1 0 0 1]
 [0 1 1 0]
 [0 1 0 1]
 [0 0 1 1]]
maxymoo
  • 35,286
  • 11
  • 92
  • 119
Hatshepsut
  • 5,962
  • 8
  • 44
  • 80
  • Possible duplicate of [Indexing a numpy array with a list of tuples](http://stackoverflow.com/questions/28491230/indexing-a-numpy-array-with-a-list-of-tuples) – maxymoo Apr 13 '17 at 01:50

2 Answers2

3

You can use fancy indexing (advanced indexing) as follows:

# 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]])
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

Try this:

[[ 1 if i in x else 0 for i in range(n) ] for x in itertools.combinations( range(n), ct )]
MaThMaX
  • 1,995
  • 1
  • 12
  • 23