[英]Fill numpy array by indexing with 2d array
我有一個 2d numpy array of zeros subbins
和一個 2d numpy array of index into it combos
。 例如
p = 4
combos = np.asarray(list(itertools.combinations(range(p),3)))
subbins = np.zeros(shape=(len(combos),p))
數組看起來像這樣
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.]]
如何使用combos
來索引subbins
並指定值不反復-如Python的越好? 即我想要的輸出是這樣的:
output = [[1. 1. 1. 0.]
[1. 1. 0. 1.]
[1. 0. 1. 1.]
[0. 1. 1. 1.]]
我們可以使用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.