NumPy | diagonal method
Start your free 7-days trial now!
NumPy's diagonal(~) method returns the diagonal of the input array.
From NumPy 1.9 onwards, diagonal(~) returns a read-only view of the input array. Modifying this view will result in an error. If you want to modify it, use NumPy's copy(~) method.
The NumPy team is considering to change the behavior from read-only to both read-and-write in future versions.
Parameters
1. a | array-like
The input array.
2. offsetlink | int | optional
If offset is positive, the next offset diagonal on the top will be returned instead. If negative, then diagonal on the bottom will be returned instead. By default, offset=0.
3. axis1 | int | optional
The first axis from which to extract the diagonal. By default, axis1=0.
4. axis2 | int | optional
The second axis from which to extract the diagonal. By default, axis2=0.
You only need to consider the parameters axis1 and axis2 only when dealing with arrays that have 3 or more dimensions.
Return value
A NumPy array that contains the diagonals of the input array.
Examples
Consider the following 2D array:
a
array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
To get the main diagonal:
np.diagonal(a)
array([1, 5, 9])
Offset
To get the diagonal with offset 1:
np.diagonal(a, offset=1)
array([2, 6])
To get the diagonal with offset -2:
np.diagonal(a, offset=-2)
array([7])