Pandas DataFrame Diagonal

In this article, we are going to learn how to find the diagonal of a square dataframe?
Submitted by Pranit Sharma, on November 09, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Diagonal in pandas DataFrame is that coordinate where the row coordinate and column coordinate is the same.

Finding the diagonal of a square dataframe

In order to find out the diagonal of a DataFrame, we either need to access it as a series or DataFrame, here we are going to store it as a series.

The numpy.diag() method will help us to find out the diagonal values of the object passed inside it hence we will pass our DataFrame as a parameter and the result will be converted into a series.

Let us understand with the help of an example,

Python program to find the diagonal of a square dataframe

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating DataFrame
df = pd.DataFrame(np.random.rand(3,3) * 5,
    columns = list('abc'),
    index = list('ABC')

# Display dataframe
print('Original DataFrame:\n',df,'\n')

# Finding out the diagonal
res = pd.Series(np.diag(df), index=[df.index, df.columns])

# Display result


The output of the above program is:

Example: Pandas DataFrame Diagonal

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.