填充numpy 2D阵列的多个对角线元素

时间:2015-01-28 15:19:17

标签: numpy

填充2维numpy数组的多个对角元素(但不是全部)的最佳方法是什么。 我知道numpy.fill_diagonal是填充所有对角元素的推荐方法。

目前我只使用循环:

for i in a_list_of_indices: a_2d_array[i,i] = num

如果数组很大且要填充的对角线元素的数量也很大,那么有比上面更好的方法。

1 个答案:

答案 0 :(得分:0)

您可以在不循环的情况下使用它:

a_2d_array[a_list_of_indices,a_list_of_indices] = num

示例:

a_2d_array = np.zeros((5,5))
a_list_of_indices = [2, 3]

返回:

array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])