Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

# What is the numpy.diagflat() method from NumPy in Python? Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

### 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.

### Code

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

### 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.

RELATED TAGS

python
communitycreator

CONTRIBUTOR Onyejiaku Theophilus Chidalu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring

Learn in-demand tech skills in half the time 