简体   繁体   English

通过使用二维数组索引来填充 numpy 数组

[英]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 .我有一个 2d numpy array of zeros subbins和一个 2d numpy array of index 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?如何使用combos来索引subbins并指定值不反复-如Python的越好? Ie the output I want is this:即我想要的输出是这样的:

output = [[1. 1. 1. 0.]
 [1. 1. 0. 1.]
 [1. 0. 1. 1.]
 [0. 1. 1. 1.]]

We can use np.put_along_axis :我们可以使用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.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM