Thursday, September 4, 2025
HomeLanguagesnumpy.diag() in Python

numpy.diag() in Python

numpy.diag(a, k=0) : Extracts and construct a diagonal array 
Parameters : 

a : array_like 
k : [int, optional, 0 by default]
          Diagonal we require; k>0 means diagonal above main diagonal or vice versa.

Returns : 

ndarray

Python




# Python Programming illustrating
# numpy.diag method
  
import numpy as geek
  
# matrix creation by array input
a = geek.matrix([[1, 21, 30], 
                 [63 ,434, 3], 
                 [54, 54, 56]])
  
print("Main Diagonal elements : \n", geek.diag(a), "\n")
  
print("Diagonal above main diagonal : \n", geek.diag(a, 1), "\n")
  
print("Diagonal below main diagonal : \n", geek.diag(a, -1))


Output : 
 

Main Diagonal elements : 
 [  1 434  56] 

Diagonal above main diagonal : 
 [21  3] 

Diagonal below main diagonal : 
 [63 54]

References : 
https://docs.scipy.org/doc/numpy/reference/generated/numpy.diagflat.html#numpy.diagflat 
Note : 
These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them 

This article is contributed by Mohit Gupta_OMG 😀. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11798 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6748 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS