numpy.diag_indices() in Python (original) (raw)
Last Updated : 08 Mar, 2024
The numpy.diag_indices() function returns indices in order to access the elements of main diagonal of a array with minimum dimension = 2. Returns indices in the form of tuple.
to access the main diagonal of an array.
Syntax: numpy.diag_indices(n, n_dim = 2)
Parameters :
n : size of array, for which indices of diag elements are required along each dimension n_dim : [int, optional]number of dimensions.
Return :
Indices(as tuples) to access diagonal elements.
Code 1 :
Python3
import
numpy as geek
d
=
geek.diag_indices(
5
)
print
(
"Indices of diagonal elements as tuple : "
)
print
(d,
"\n"
)
array
=
geek.arange(
16
).reshape(
4
,
4
)
print
(
"Initial array : \n"
, array)
d
=
geek.diag_indices(
4
)
array[d]
=
25
print
(
"\n New array : \n"
, array)
Output :
Indices of diagonal elements as tuple : (array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4]))
Initial array : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]]
New array : [[25 1 2 3] [ 4 25 6 7] [ 8 9 25 11] [12 13 14 25]]
Code 2 : Manipulating 2D array
Python
import
numpy as geek
d
=
geek.diag_indices(
3
,
2
)
array
=
geek.arange(
12
).reshape(
4
,
3
)
array[d]
=
111
print
(
"Manipulated array : \n"
, array)
Output :
Manipulated array : [[111 1 2] [ 3 111 5] [ 6 7 111] [ 9 10 11]]
Code 3 : Manipulating 3D array
Python
import
numpy as geek
d
=
geek.diag_indices(
1
,
2
)
print
(
"Diag indices : \n"
, d)
array
=
geek.ones((
2
,
2
,
2
), dtype
=
geek.
int
)
print
(
"Initial array : \n"
, array)
array[d]
=
0
print
(
"New array : \n"
, array)
Output :
Diag indices : (array([0]), array([0])) Initial array : [[[1 1] [1 1]]
[[1 1] [1 1]]] New array : [[[0 0] [1 1]]
[[1 1] [1 1]]]
Note :
These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.