Write a program in Python to modify the diagonal of a given DataFrame by 1


Assume, you have a dataframe

0 1 2

0 10 20 30 1 40 50 60 2 70 80 90

The result for replaced 1 by diagonal of a dataframe is −

0 1 2
0 1 20 30 1 40 1 60 2 70 80 1

Solution

To solve this, we will follow the steps given below −

  • Define a dataframe

  • Create nested for loop to access all rows and columns,

for i in range(len(df)):
   for j in range(len(df)):
  • Check if the condition to match the diagonals, if it is matched then replace the position by 1. It is defined below,

if i == j:
   df.iloc[i ,j] = 1

Example

Let us see the below implementation to get a better understanding,

import pandas as pd
import numpy as np
data = [[10,20,30],[40,50,60],[70,80,90]]
df = pd.DataFrame(data)
print("Original DataFrame is\n ", df)
for i in range(len(df)):
   for j in range(len(df)):
      if i == j:
         df.iloc[i ,j] = 1

print("Modified DataFrame is\n" ,df)

Output

Original DataFrame is
   0  1  2
0 10 20 30
1 40 50 60
2 70 80 90
Modified DataFrame is
  0  1  2
0 1 20 30
1 40 1 60
2 70 80 1

Updated on: 24-Feb-2021

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements