Kodeclik Blog


Python numpy.diag()

The numpy.diag() function in Python extracts the diagonal elements of an array or creates a diagonal array from a given array. In this post, we will explore the various ways in which the numpy.diag() function can be used in Python.
The numpy.any() function returns True if any element in the input array a evaluates to True. Otherwise, it returns False. The function can be used with one-dimensional and multi-dimensional arrays.
Consider the following simple program to illustrate how numpy.diag() works:
Here we are constructing a 3x3 array which is really a magic square. Note that all rows, columns, and diagonals sum upto 15. From this array we are extracting the diagonal using the numpy.diag() function. The output is:
You can use numpy.diag() to extract not just the main diagonal but also offset diagonals. Consider the following update to the program:
The second (optional) argument to diag is the offset from the main diagonal. Thus if this offset is 0, then we get back the main diagonal (as printed by the first print line in the above program). Positive offsets give us diagonals to the right and above, and negative offsets give us diagonals to the left and below.
Thus the output is:
Note that the main diagonal is of length 3. The diagonals with offsets 1 and -1 are of length 2. Finally, the diagonals with offsets 2 and -2 are of length 1.
A second use of the numpy.diag() function is to actually create a matrix (numpy array) with the specified input as the diagonal. Consider:
In this case x is just a 1x3 array (not a full matrix or 3x3 array). When we call numpy.diag() with a 1D array such as done here, it will output a 2D array with the given array as the diagonal. Thus the output is:
We can also adapt this to provide offsets, like so:
In this case we are specifying that [1, 2, 3] is not the main diagonal but rather the diagonal to the right (and above) the main diagonal. This means that the matrix must be of size 4x4, rather than 3x3. True enough the output will be:
Thus, in conclusion, numpy.diag() function is a powerful tool for extracting diagonal elements from an array or creating a diagonal matrix from a 1D array. The function is simple to use and has several useful parameters that allow for customization. Write to us about how you used it in your programs!
If you liked learning about numpy.diag() learn about the numpy.eye() function!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2024. All rights reserved.