Is there any pythonic way of filling up the diagonal values in a 2D array? Or do we have to go with the conventional way:
for i in range(size):
for j in range(size):
if i==j:
data[i][j] = -1
Is there any pythonic way of filling up the diagonal values in a 2D array? Or do we have to go with the conventional way:
for i in range(size):
for j in range(size):
if i==j:
data[i][j] = -1
You could use numpy.fill_diagonal().
a = np.zeros((3, 3), int)
np.fill_diagonal(a, 5)
a
OUTPUT
array([[5, 0, 0],
[0, 5, 0],
[0, 0, 5]])
Refer to https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.fill_diagonal.html.
You can do it with 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.]]