填充 numpy 二维数组的多个对角线元素

Filling multiple diagonal elements of a numpy 2D array

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

目前我正在使用一个循环:

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

如果数组很大,要填充的对角线元素个数也很多,有没有比上面更好的方法

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

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]

returns:

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.]])