我试图同时更新一组行的多个列。(在我的例子中,列的数量和行的数量是一样的——我正在制作一个相似性矩阵,但一般来说,这并不重要)。有没有比下面的例子更有效的方法?--我愿意使用
python lists
,
pandas
或
numpy
示例1-两个嵌套
for
循环
adj_mat = np.array([[1,1,1,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0],
[1,1,1,1,0,0,0,0,0],
[0,0,1,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,1,0,0],
[0,0,0,0,0,1,1,1,1],
[0,0,0,0,0,0,1,1,1],
[0,0,0,0,0,0,1,1,1]])
inlier_mask = np.array([False, False, False, True, True, True, False,
False, False])
inlier_idx = np.array(np.nonzero(inlier_mask))[0].tolist()
for i in inlier_idx:
for j in inlier_idx:
adj_mat[i,j] += 1
print(adj_mat)
输出:
[[1 1 1 0 0 0 0 0 0]
[1 1 1 0 0 0 0 0 0]
[1 1 1 1 0 0 0 0 0]
[0 0 1 2 2 2 0 0 0]
[0 0 0 2 2 2 0 0 0]
[0 0 0 2 2 2 1 0 0]
[0 0 0 0 0 1 1 1 1]
[0 0 0 0 0 0 1 1 1]
[0 0 0 0 0 0 1 1 1]]
示例2-只有一个
对于
环
adj_mat = np.array([[1,1,1,0,0,0,0,0,0],
[1,1,1,0,0,0,0,0,0],
[1,1,1,1,0,0,0,0,0],
[0,0,1,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,1,0,0],
[0,0,0,0,0,1,1,1,1],
[0,0,0,0,0,0,1,1,1],
[0,0,0,0,0,0,1,1,1]])
inlier_mask = np.array([False, False, False, True, True, True, False,
False, False])
inlier_idx = np.array(np.nonzero(inlier_mask))[0].tolist()
for i in inlier_idx:
adj_mat[i,inlier_idx] += 1
输出:
[[1 1 1 0 0 0 0 0 0]
[1 1 1 0 0 0 0 0 0]
[0 0 1 2 2 0 0 0]
[0 0 0 2 2 0 0 0 0]
[0 0 0 0 0 1 1 1 1]
[0 0 0 0 0 1 1 1]
[0 0 0 0 0 1 1 1]]
是否有如下解决方案:
adj_mat[inlier_idx,inlier_idx] += 1
不需要循环就可以实现?