Dr. Andrew
Dr. Andrew

Reputation: 2621

Fill numpy array by indexing with 2d array

I have a 2d numpy array of zeros subbins, and a 2d numpy array of indices into it combos. For example

p = 4
combos = np.asarray(list(itertools.combinations(range(p),3)))
subbins = np.zeros(shape=(len(combos),p))

The arrays look like this

combos = [
     [0, 1, 2],
     [0, 1, 3],
     [0, 2, 3],
     [1, 2, 3],
]
subbins = [
     [0, 0, 0, 0],
     [0, 0, 0, 0],
     [0, 0, 0, 0],
     [0, 0, 0, 0],
]

How can I use combos to index into subbins and assign values without iterating - as pythonic as possible? I.e. the output I want is this:

output = [
     [1, 1, 1, 0],
     [1, 1, 0, 1],
     [1, 0, 1, 1],
     [0, 1, 1, 1],
]

Upvotes: 1

Views: 371

Answers (1)

yatu
yatu

Reputation: 88236

We can use np.put_along_axis:

np.put_along_axis(subbins, combos, 1, axis=1)

print(subbins)
array([[1., 1., 1., 0.],
       [1., 1., 0., 1.],
       [1., 0., 1., 1.],
       [0., 1., 1., 1.]])

Upvotes: 2

Related Questions