What is the numpy.diagflat() method from NumPy in Python?

Overview

Python’s diagflat() function creates a 2D array with the flattened input as a diagonal.

A flattened array is simply a 1D array. Therefore in this case of the diagflat() function, the input data is flattened (converted to a 1D array) and then used as the diagonal of the output 2D array.

Syntax

numpy.diagflat(v, k=0)

Parameter value

The diagflat() function takes the following parameter values:

  • v: This represents the array_like object which is flattened and set as the k-th diagonal of the output.
  • k: This represents the diagonal to set, 0 is the main diagonal, or the default diagonal, a positive or negative k is the number of diagonals above or below the main diagonal, respectively. This is optional.

Return value

The diagflat() function returns the 2D output array.

Illustration of how the diagflat() function works

Code

import numpy as np
# creating an array
myarray = np.array([[1,2], [3,4]])
# implementing the diagflat() function
diagarray = np.diagflat(myarray, 1)
print(myarray)
print(diagarray)

Explanation

  • Line 1: We import the numpy library.
  • Line 4: We create an array, myarray, using the array() function.
  • Line 7: We implement the diagflat() function on the given array, myarray, with the diagonal to start above the main diagonal at 1. The result is assigned to a new variable daigarray.
  • Line 10: We print the existing array myarray.
  • Line 11: We print the newly created 2D diagonal array, diagarray.

Free Resources