
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Write a Python program to sort a given DataFrame by name column in descending order
- Write a Python program to reshape a given dataframe in different ways
- Write a program in Python to convert a given dataframe to a LaTex document
- Write a program in Python to perform flatten the records in a given dataframe by C and F order
- Write a program in Python to filter City column elements by removing the unique prefix in a given dataframe
- Write a program in Python to localize Asian timezone for a given dataframe
- Write a program in Python to transpose the index and columns in a given DataFrame
- Write a Python code to rename the given axis in a dataframe
- Write a program in Python to count the total number of leap years in a given DataFrame
- Write a program in Python to remove first duplicate rows in a given dataframe
- Write a Python program to quantify the shape of a distribution in a dataframe
- Write a program in Python to count the records based on the designation in a given DataFrame
- Write a program in Python to caluculate the adjusted and non-adjusted EWM in a given dataframe
- Write a Python code to filter palindrome names in a given dataframe
- Write a Python code to fill all the missing values in a given dataframe
Advertisements