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.

Finding the diagonal of a square dataframe

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

Rows in pandas are generally marked with the index number but in pandas, we can also assign index names according to the needs. In pandas, we can create, read, update, and delete a column or row value.

Columns are the different fields that contain their particular values when we create a DataFrame. We can perform certain operations on both row & column values.

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 code 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
print("Result:\n",res)

Output:

Example: Pandas DataFrame Diagonal

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.