How To Get The Diagonal Elements Of A Matrix In Python

Working with matrices is a common task in programming, especially when dealing with mathematical or machine-learning problems. In this tutorial, we will learn how to extract the diagonal elements of a matrix using Python.

This can be useful when you want to find the trace of a matrix, which is the sum of the diagonal elements, or when you simply need the diagonal elements of a matrix for further processing.

To accomplish this, we will use Python’s built-in support for lists and slicing, as well as the popular numerical libraries numpy and pandas.

Step 1: Creating a Matrix Using Lists

In Python, we can represent a matrix using a list of lists, where each inner list represents a row of the matrix. Here’s a 3×3 matrix example:

Step 2: Extracting the Diagonal Elements

We can extract the diagonal elements of a matrix using simple list comprehension and slicing. The diagonal elements are those where the row and column number are the same, i.e., the indices are equal. For a 3×3 matrix, this would be the elements at positions (0,0), (1,1), and (2,2).

To achieve this, you can use the following code:

In this code, we use the range function to iterate through the row numbers and indexes, and slice the diagonal elements using the same index for both row and column of the matrix.

Running this code on our example matrix would result in the following diagonal elements:

[10, 50, 90]

Step 3: Using Numpy to Get the Diagonal Elements

Another common way to work with matrices in Python is by using the numpy library. If you don’t have numpy installed, you can install it using pip:
pip install numpy
Now, let’s convert our list-based matrix to a numpy array and extract the diagonal elements using the numpy.diagonal() function:

Executing this code will give us a numpy array containing the diagonal elements:

array([10, 50, 90])

Step 4: Getting the Diagonal Elements Using Pandas

Lastly, let’s extract the diagonal elements using the pandas library. This library provides a DataFrame data structure which can be used to represent a matrix.

To get started with pandas, install it using pip if you don’t have it yet:
pip install pandas
Now, let’s create a pandas DataFrame from our list-based matrix and extract the diagonal elements using the pandas.DataFrame.iloc[] indexer:

This will give us a list containing the diagonal elements:

[10, 50, 90]

Full Code


In this tutorial, we discussed how to extract diagonal elements from a matrix using Python lists, numpy, and pandas. You can choose the method that best fits the data structure and libraries you are already using in your project. Each of these approaches provides a simple and efficient way to extract diagonal elements from a matrix in Python.