Pandas fill diagonal

In pandas, the ‘fill_diag’ method is used to fill the diagonal elements of a DataFrame or a Series with a specified value. The diagonal elements of a DataFrame are the elements that lie on the main diagonal, which extends from the top left to the bottom right of the DataFrame. The ‘fill_diag’ method allows you to easily set all the diagonal elements to a specific value of your choice.

The syntax for using the ‘fill_diag’ method is as follows:

   
   import pandas as pd

   # Create a DataFrame
   df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

   # Fill the diagonal elements with a specified value
   filled_df = df.fill_diag(value)
   
   

Let’s take a look at an example to understand how the ‘fill_diag’ method works:

   
   import pandas as pd
   
   # Create a DataFrame
   df = pd.DataFrame([[1, 0, 0], [0, 5, 0], [0, 0, 9]])

   # Fill the diagonal elements with a value of 10
   filled_df = df.fill_diag(10)
   
   print(filled_df)
   
   

Output:

   
      0   1   2
   0  10   0   0
   1   0  10   0
   2   0   0  10
   
   

As you can see in the example above, the ‘fill_diag’ method sets all the diagonal elements of the DataFrame to the specified value, which in this case is 10.

Leave a comment