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

PythonPandasServer Side ProgrammingProgramming

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
raja
Published on 11-Feb-2021 10:10:34
Advertisements