Trusted answers to developer questions

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.

The ** diagonal() function** in Python is simply used to return a specified diagonal from a given 2D array.

```
numpy.diagonal(a, offset=0, axis1=0, axis2=1)
```

Note: To use

`numpy.diagonal()`

function, first`import numpy`

.

The `diagonal()`

function takes the following parameter values:

: This represents the`a`

`array_like`

object from which the diagonal is taken.: This represents the offset to the diagonal from the main diagonal. It could take a negative or positive integer value. The default to the main diagonal is`offset`

`0`

. This is optional.: This represents the axis to be used as the first axis of the`axis1`

`2D`

sub-arrays from which the diagonals should be taken. The default value is`0`

.: This represents the axis to be used as the second axis of the`axis2`

`2D`

sub-arrays from which the diagonals should be taken. The default value is`1`

.

The `diagonal()`

function returns a diagonal array.

import numpy as np# creating an arraymyarray = np.arange(9).reshape(3, 3)# implementing the diagonal() functiondiagarray = np.diagonal(myarray, 0, 0, 1)print(myarray)print(diagarray)

Implementing the diagonal() function

**Line 1**: We import the`numpy`

library.**Line 4**: We create a 2D array`myarray`

of 9 elements with a dimension of`3 by 3`

, that is`3`

rows and`3`

columns, using the`arange()`

function.**Line 7**: We implement the`diag()`

function on the array`myarray`

using the main diagonal`k = 0`

, default`axis1`

,`0`

, and a default`axis2`

,`0`

. The result is assigned to a new variable`diagarray`

.**Line 9**: We print the array`myarray`

.**Line 10**: We print the new diagonal array`diagarray`

.

RELATED TAGS

numpy

python

communitycreator

diagonal

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

Related Courses