1

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],
]
umläute
32k11 gold badges75 silver badges135 bronze badges
asked Feb 19, 2020 at 11:04

1 Answer 1

2

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.]])
answered Feb 19, 2020 at 11:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.