Last active
July 31, 2023 22:07
-
-
Save selva86/4e79a30e946df77c1b4d387561a24291 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import pandas as pd | |
dfc = pd.DataFrame(np.zeros((1000, 1000), dtype='int')) |
np.fill_diagonal(dfc.values,1)
dfc.head(10)
#And
for i in range((dfc.shape[0])): #
dfc.iat[i,i] = 1
dfc.head(5)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are 2 methods we can put 1's in every diagonal location of the dataframe.
#Method1:
np.fill_diagonal(dfc.values,1)
#Method using for loop and iat
"""
=> for i in range(dfc.shape[0]): it will iterate over all row indices of the DataFrame dfc. Since dfc.shape[0] gives the number of rows in the DataFrame, the loop will go from 0 to dfc.shape[0] - 1, which means it will cover all the row indices.
=> dfc.iat[i,i] = 1: it sets the diagonal element at index (i, i) to 1. In each iteration of the loop, it moves along the diagonal and sets the diagonal elements one by one to 1.
to be precise,in line dfc.iat[i,i],it accesses the DataFrame element at the ith row and ith column, which corresponds to the diagonal position of the DataFrame.
we can use alternative for loop as : for i in range(min(dfc.shape)) and then dfc.iat[i,i] = 1
"""
for i in range(dfc.shape[0]):
dfc.iat[i,i] =1