0

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
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
anshul
  • 1
  • Pretty easy to do as a list comprehension: `[[-1 if i == j else 0 for j in range(size)] for i in range(size)]` – Patrick Haugh Sep 24 '18 at 18:29
  • @Daniel don't think that will work the way you want it to – user3483203 Sep 24 '18 at 18:36
  • using numpy: numpy.diag([-1]*size) – Daniel Sep 24 '18 at 18:39
  • As several people state here, numpy has pretty convenient functions for that. However, with regards to your looping algorithm, you should note that if you have a conditional within a nested loop which assures equality of the loop counters for the only code inside - you simply don't need the nested loop. Just use a single loop and its counter for each index... – SpghttCd Sep 24 '18 at 18:40
  • There is no need to create an inner loop, if all you do there is `if i == j`. So if you just have that outer loop it will probably be fine, unless your array is really large. Otherwise use numpy. – Feodoran Sep 24 '18 at 18:41

2 Answers2

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.

parthagar
  • 880
  • 1
  • 7
  • 18
0

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.]]
Martin Gergov
  • 1,556
  • 4
  • 20
  • 29