1 回答

TA貢獻1808條經(jīng)驗 獲得超4個贊
這是一種方法:
Python 中的多維索引要求您顯式索引每個單元格。所以需要先創(chuàng)建索引,然后使用如下:
ind = np.array([[2,6,7]]) # Notice the 2D array
rows = np.broadcast_to(ind.transpose(), (3,3))
cols = np.broadcast_to(ind, (3,3))
A[rows, cols]+=B # A cell from rows matrix and a corresponding cell in cols matrix together form one cell index.
輸出:
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
[1, 1, 3, 1, 1, 1, 3, 3, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
請閱讀:https ://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html
出于某種原因,雖然以下確實從中挑選出正確的矩陣A,但分配給它不起作用:
ind_1 = np.array([2,6,7])
A[ind_1,:][:, ind_1] = B # No error, but assignment does not take place
添加回答
舉報