簡體   English   中英

通過使用二維數組索引來填充 numpy 數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM