Set values on the diagonal of pandas.DataFrame

Given a pandas dataframe, we have to set values on the diagonal of pandas.DataFrame.
Submitted by Pranit Sharma, on October 10, 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.

Problem statement

Suppose, we are given a DataFrame and we need to set the values of the diagonal of this DataFrame to 0.

Setting values on the diagonal of pandas.DataFrame

We will either go row-wise or column-wise to solve this problem. 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.

Let us understand with the help of an example,

Python program to set values on the diagonal of pandas.DataFrame

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'a':[2,4,6,8,10],
    'b':[1,3,5,7,9],
    'c':[2,4,6,8,10],
    'd':[1,3,5,7,9],
    'e':[2,4,6,8,10]
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# fluctuating diagonals
df.values[[np.arange(df.shape[0])]*2] = 0

# Display result
print("Result:\n",df)

Output

The output of the above program is:

Example: Set values on the diagonal of pandas.DataFrame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.