NumPy ndarray.diagonal()
The numpy.ndarray.diagonal()
method extracts the diagonals of a NumPy array.
It returns the elements along the specified diagonal of a 2D or higher-dimensional array.
Syntax
</>
Copy
ndarray.diagonal(offset=0, axis1=0, axis2=1)
Parameters
Parameter | Type | Description |
---|---|---|
offset | int, optional | The diagonal offset from the main diagonal. A positive value selects an upper diagonal, a negative value selects a lower diagonal. |
axis1 | int, optional | The first axis of the array defining the 2D planes from which to extract diagonals. |
axis2 | int, optional | The second axis of the array defining the 2D planes from which to extract diagonals. |
Return Value
Returns a new NumPy array containing the extracted diagonal elements.
Examples
1. Extracting the Main Diagonal
In this example, we extract the main diagonal (where offset=0
) from a 3×3 matrix.
</>
Copy
import numpy as np
# Creating a 3x3 matrix
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Extracting the main diagonal
diagonal_main = arr.diagonal()
print("Main diagonal:", diagonal_main) # Output: [1 5 9]
Output:
Main diagonal: [1 5 9]
2. Extracting an Upper Diagonal
We use a positive offset
to extract an upper diagonal.
</>
Copy
import numpy as np
# Creating a 3x3 matrix
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Extracting the diagonal above the main diagonal (offset=1)
diagonal_upper = arr.diagonal(offset=1)
print("Upper diagonal:", diagonal_upper) # Output: [2 6]
Output:
Upper diagonal: [2 6]
3. Extracting a Lower Diagonal
We use a negative offset
to extract a lower diagonal.
</>
Copy
import numpy as np
# Creating a 3x3 matrix
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Extracting the diagonal below the main diagonal (offset=-1)
diagonal_lower = arr.diagonal(offset=-1)
print("Lower diagonal:", diagonal_lower) # Output: [4 8]
Output:
Lower diagonal: [4 8]
4. Extracting Diagonal from a 3D Array
For higher-dimensional arrays, axis1
and axis2
specify the plane from which the diagonal is extracted.
</>
Copy
import numpy as np
# Creating a 3D array (2 matrices of 3x3)
arr_3d = np.array([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]])
# Extracting the main diagonal from each matrix along axes 1 and 2
diagonal_3d = arr_3d.diagonal(axis1=1, axis2=2)
print("Diagonals from 3D array:\n", diagonal_3d)
Output:
Diagonals from 3D array:
[[ 1 5 9]
[10 14 18]]
Each row in the result represents the diagonal extracted from the corresponding 3×3 matrix.