在python3中填充2D数组中的对角线元素

时间:2018-09-24 18:27:24

标签: python python-3.x multidimensional-array

在2D数组中是否有任何Python方式填充对角线值? 还是我们必须遵循常规方式:

for i in range(size):
   for j in range(size):
      if i==j:
         data[i][j] = -1

2 个答案:

答案 0 :(得分:1)

您可以使用numpy.fill_diagonal()。

a = np.zeros((3, 3), int)
np.fill_diagonal(a, 5)
a

输出

array([[5, 0, 0],
       [0, 5, 0],
       [0, 0, 5]])

请参阅https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.fill_diagonal.html

答案 1 :(得分:0)

您可以使用numpy来做到这一点:

import numpy as np

ndarray = np.zeros((10,10))
np.fill_diagonal(ndarray, 1)

print(ndarray)
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]