How to Get Diagonal of NumPy Array Using diag()

  • Post author:
  • Post category:NumPy / Python
  • Post last modified:November 15, 2023
  • Reading time:17 mins read

In NumPy, you can use the numpy.diag() function in Python is used to extract the diagonal elements of an array or construct a diagonal array. This function takes an array and k as parameters and returns the diagonal array from the given array. In this article, I will explain how to use the NumPy diag() function and using how to extract or construct a diagonal array from the given array with examples.

1. Quick Examples of Diagonal of NumPy Array

If you are in a hurry, below are some quick examples of how to get NumPy diagonal in Python by using diag().


# Quick examples of diagonal of numpy array

# Example 1: Use numpy.diag() function
# To extract the main diagonal elements
arr = np.array([[9, 18, 25],[155 ,240, 68],[29, 82, 108]])
arr2 = np.diag(arr)

# Example 2: Use the above main diagonal
arr = np.array([[9, 18, 25],[155 ,240, 68],[29, 82, 108]])
arr2 = np.diag(arr, 1)

# Example 3: Use below main diagonal
arr = np.array([[9, 18, 25],[155 ,240, 68],[29, 82, 108]])
arr2 = np.diag(arr, k=-1)

# Example 4: Construct diagonal from numpy array
arr = np.array([3, 7, 12, 18])
arr2 = np.diag(arr)

# Example 5: Use diag to numpy row vector
arr = np.array([[3, 7, 12, 18]])
arr2 = np.diag(arr[0])

2. Syntax of numpy.diag()

Following is the syntax to create numpy.diag() function.


# Syntax of numpy.diag()
numpy.diag(arr, k=0)

2.1 Parameter of diag()

  • arr: The input array from which the diagonal elements are extracted. For a 2-D array, it returns a copy of its k-th diagonal. For a 1-D array, return a 2-D array with arr on the k-th diagonal.
  • k: The default is 0. Use k > 0 to get diagonals above the main diagonal, and k < 0 to get diagonals below the main diagonal.

2.2 Return Value of diag()

This function is used to extract diagonal or constructed diagonal arrays.

3. Usage numpy.diag() To Extract Diagonal

Numpy diag() function is used to extract or construct a diagonal 2-D array. It contains two parameters: an input array and k, which decides the diagonal, i.e., k=0 for the main diagonal, k=1 for the above main diagonal, or k=-1 for the below diagonal. It is used to perform the mathematical and statistics operation on the multidimensional array.

3.1 Use Main Diagonal Elements

You can use numpy.diag() to extract the diagonal elements from a 2D NumPy array. For instance, numpy.diag(arr) is used to extract the main diagonal elements from the array arr. The resulting arr2 variable will be a 1D array containing the values [9, 240, 108], which are the diagonal elements of the original array.


# Import numpy
import numpy as np

# Create input array
arr = np.array([[9, 18, 25],[155 ,240, 68],[29, 82, 108]])
print("Original array:\n",arr)

# Use numpy.diag() function
# To extract the main diagonal elements
arr2 = np.diag(arr)
print("Main Diagonal elements:\n",arr2)

Yields below output.

numpy diagonal

3.2 Use Above the Main Diagonal

If you provide k=1, it will return the diagonal one above the main diagonal. If you want to extract the diagonal elements above the main diagonal, you can use a positive value for the k parameter in numpy.diag().

The below example, k=1 gives you the diagonal element that is one position above the main diagonal. Adjust the value of k as needed to extract diagonals at different positions above the main diagonal.


# Use above main diagonal
arr2 = np.diag(arr, 1)
print("Diagonal one above the main diagonal:\n",arr2)

Yields below output.

numpy diagonal

3.3 Use Below the Main Diagonal

When you use k=-1 with numpy.diag(), it returns the diagonal elements below the main diagonal. So, you can see that k=-1 gives you the diagonal elements below the main diagonal in the specified array. The k parameter is a powerful tool when working with diagonals in NumPy arrays.


# Use below main diagonal
arr2 = np.diag(arr, k=-1)
print("Diagonal below the main diagonal:\n",arr2)

# Output:
# Diagonal below the main diagonal:
#  [155  82]

4. Take a 4×4 Matrix and Apply the diag() Function

Let’s create a 4×4 matrix and apply the numpy.diag() function to extract its main diagonal. The numpy.diag() function is used here to extract the main diagonal elements from the 4×4 matrix. From the below example, it returns 6, 35, and 27.


# Create a 4x4 array
arr = np.array([[6,9,15],[24,35,26],[19,8,27],[41,53,15]])
print("Original 4x4 array:\n", arr)

# Apply numpy.diag() to extract the main diagonal
arr2 = np.diag(arr)
print("Main Diagonal elements:\n",arr2)

# Output:
# Original 4x4 array:
#  [[ 6  9 15]
#  [24 35 26]
#  [19  8 27]
#  [41 53 15]]
# Main Diagonal elements:
#  [ 6 35 27]

# Above main diagonal
arr2 = np.diag(arr, 1)
print("Diagonal above the main diagonal:\n",arr2)

# Output:
# Diagonal above the main diagonal:
# [ 9 26]

# Below main diagonal
arr2 = np.diag(arr, -1)
print("Diagonal below the main diagonal:\n",arr2)

# Output:
# Diagonal below the main diagonal:
# [24  8 15]

5. Use Construct Diagonal From Python NumPy Array

If you want to construct a diagonal matrix from a 1D NumPy array, you can use the numpy.diag() function. For example, np.diag(arr) creates a 4×4 matrix with the provided 1D array as its diagonal elements. You can replace arr with any other 1D array to construct a diagonal matrix with different diagonal elements.


import numpy as np

# Create a 1D array
arr = np.array([3, 7, 12, 18])
print("Original 1D array:\n",arr)

# Construct a diagonal matrix 
# Using numpy.diag()
arr2 = np.diag(arr)
print("Constructed Diagonal Matrix:\n",arr2)

# Output:
# Original 1D array:
#  [ 3  7 12 18]
# Constructed Diagonal Matrix:
#  [[ 3  0  0  0]
#  [ 0  7  0  0]
#  [ 0  0 12  0]
#  [ 0  0  0 18]]

You want to create a diagonal matrix from a 1D array (in this case, a row vector). In this version, I removed the extra square brackets around the row vector (arr = np.array([[3, 7, 12, 18]])) because np.diag() expects a 1D array for constructing the diagonal matrix.


# Create a 1D array
arr = np.array([[3, 7, 12, 18]])
print("Original 1D array:\n",arr)

# Use diag to numpy row vector
arr2 = np.diag(arr[0])
print("Constructed Diagonal Matrix:\n",arr2)

Yields the same output as above.

Frequently Asked Questions

What does numpy.diag() do?

numpy.diag() is a NumPy function that serves two main purposes:
Extracting Diagonal Elements: Given a 2D array or matrix, it returns a 1D array containing the elements of the main diagonal.
Constructing Diagonal Array: Given a 1D array, it constructs a 2D diagonal array with the specified 1D array as its diagonal elements.

How do I extract the main diagonal of a NumPy array?

To extract the main diagonal of a NumPy array, you can use the numpy.diag() function. The numpy.diag() function returns the main diagonal of a 2D array or constructs a 2D array with the specified 1D array as its diagonal elements.

How do I construct a diagonal array from a 1D array?

To construct a diagonal array from a 1D array in NumPy, you can use the numpy.diag() function. This function takes a 1D array as input and returns a 2D array with the input array as its diagonal elements.

Can I get diagonals other than the main diagonal?

You can use the optional parameter k in numpy.diag() to specify the diagonal offset. A positive k refers to diagonals above the main diagonal, and a negative k refers to diagonals below the main diagonal.

How do I get the diagonal one position above the main diagonal?

To get the diagonal one position above the main diagonal of a NumPy array, you can use the numpy.diag() function with the k parameter set to 1.

What if I have a row vector and want to create a diagonal matrix?

If you have a row vector and you want to create a diagonal matrix from it, you can use the numpy.diag() function. The row vector will be treated as a 1D array, and numpy.diag() will construct a 2D array with the row vector as its main diagonal elements.

Conclusion

In this article, I have explained how to use numpy.diag() method syntax, parameters, and usage of how to extract a diagonal or construct a diagonal array from the given array with examples.

Happy Learning!!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.

Leave a Reply