1 回答
![?](http://img1.sycdn.imooc.com/54586431000103bb02200220-100-100.jpg)
TA贡献1808条经验 获得超4个赞
这是一种方法:
Python 中的多维索引要求您显式索引每个单元格。所以需要先创建索引,然后使用如下:
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
添加回答
举报