Skip to content

Instantly share code, notes, and snippets.

@selva86
Last active July 31, 2023 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save selva86/4e79a30e946df77c1b4d387561a24291 to your computer and use it in GitHub Desktop.
Save selva86/4e79a30e946df77c1b4d387561a24291 to your computer and use it in GitHub Desktop.
import numpy as np
import pandas as pd
dfc = pd.DataFrame(np.zeros((1000, 1000), dtype='int'))
@Prakashmoharana1985
Copy link

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

@Prakashmoharana1985
Copy link

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