|
| 1 | +--- |
| 2 | +Title: '.diagonal()' |
| 3 | +Description: 'Returns the specified diagonal elements of an array.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Arrays' |
| 9 | + - 'Linear Algebra' |
| 10 | + - 'Matrices' |
| 11 | + - 'NumPy' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/data-science' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`.diagonal()`** method returns the specified diagonal elements of a NumPy array. For 2D arrays, the diagonal consists of elements where the row index equals the column index (or with an offset). For multi-dimensional arrays, the axes specified by `axis1` and `axis2` define the matrix dimensions from which to extract the diagonal. |
| 18 | + |
| 19 | +Unlike [`.trace()`](https://www.codecademy.com/resources/docs/numpy/ndarray/trace), which returns the sum of diagonal elements, `.diagonal()` returns the actual diagonal elements as an array. This method typically returns a view rather than a copy, making it memory-efficient for large arrays. |
| 20 | + |
| 21 | +## Syntax |
| 22 | + |
| 23 | +```pseudo |
| 24 | +ndarray.diagonal(offset=0, axis1=0, axis2=1) |
| 25 | +``` |
| 26 | + |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `offset` (Optional): The diagonal offset from the main diagonal. A positive value selects a diagonal above the main diagonal, while a negative value selects one below. Default is `0` (main diagonal). |
| 30 | +- `axis1` (Optional): The axis to be used as the first axis of the 2D sub-arrays from which the diagonals should be taken. Default is `0`. |
| 31 | +- `axis2` (Optional): The axis to be used as the second axis of the 2D sub-arrays from which the diagonals should be taken. Default is `1`. |
| 32 | + |
| 33 | +**Return value:** |
| 34 | + |
| 35 | +Returns an array containing the diagonal elements. For 2D arrays, this is a 1D array. For higher-dimensional arrays, the result has one fewer dimension than the input. |
| 36 | + |
| 37 | +## Example 1: Extracting Diagonals from 2D and Rectangular Arrays |
| 38 | + |
| 39 | +This example demonstrates how to extract diagonals from both square and rectangular arrays using different `offset` values: |
| 40 | + |
| 41 | +```py |
| 42 | +import numpy as np |
| 43 | + |
| 44 | +# Create a 3×3 square array |
| 45 | +square = np.array([[1, 2, 3], |
| 46 | + [4, 5, 6], |
| 47 | + [7, 8, 9]]) |
| 48 | + |
| 49 | +print("Square array:") |
| 50 | +print(square) |
| 51 | + |
| 52 | +print("\nMain diagonal:", square.diagonal()) |
| 53 | +print("Upper diagonal (offset=1):", square.diagonal(offset=1)) |
| 54 | +print("Lower diagonal (offset=-1):", square.diagonal(offset=-1)) |
| 55 | + |
| 56 | +# Create a 4×3 rectangular array |
| 57 | +rectangular = np.array([[1, 2, 3], |
| 58 | + [4, 5, 6], |
| 59 | + [7, 8, 9], |
| 60 | + [10, 11, 12]]) |
| 61 | + |
| 62 | +print("\nRectangular array:") |
| 63 | +print(rectangular) |
| 64 | + |
| 65 | +print("\nMain diagonal:", rectangular.diagonal()) |
| 66 | +print("Upper diagonal (offset=1):", rectangular.diagonal(offset=1)) |
| 67 | +print("Lower diagonal (offset=-2):", rectangular.diagonal(offset=-2)) |
| 68 | +``` |
| 69 | + |
| 70 | +The output produced by this code is: |
| 71 | + |
| 72 | +```shell |
| 73 | +Square array: |
| 74 | +[[1 2 3] |
| 75 | + [4 5 6] |
| 76 | + [7 8 9]] |
| 77 | + |
| 78 | +Main diagonal: [1 5 9] |
| 79 | +Upper diagonal (offset=1): [2 6] |
| 80 | +Lower diagonal (offset=-1): [4 8] |
| 81 | + |
| 82 | +Rectangular array: |
| 83 | +[[ 1 2 3] |
| 84 | + [ 4 5 6] |
| 85 | + [ 7 8 9] |
| 86 | + [10 11 12]] |
| 87 | + |
| 88 | +Main diagonal: [1 5 9] |
| 89 | +Upper diagonal (offset=1): [2 6] |
| 90 | +Lower diagonal (offset=-2): [7 11] |
| 91 | +``` |
| 92 | + |
| 93 | +For rectangular matrices, the diagonal length is determined by the smaller dimension, and different offsets extract parallel diagonals above or below the main one. |
| 94 | + |
| 95 | +## Example 2: Using `.diagonal()` with Multi-Dimensional Arrays |
| 96 | + |
| 97 | +This example demonstrates how to extract diagonals from higher-dimensional arrays by specifying axes: |
| 98 | + |
| 99 | +```py |
| 100 | +import numpy as np |
| 101 | + |
| 102 | +# Create a 3D array (2x3x3) |
| 103 | +array_3d = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], |
| 104 | + [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]) |
| 105 | +print("3D array shape:", array_3d.shape) |
| 106 | +print("3D array:") |
| 107 | +print(array_3d) |
| 108 | + |
| 109 | +# Extract diagonal from the last two dimensions |
| 110 | +diag_default = array_3d.diagonal() |
| 111 | +print("\nDiagonal (axis1=0, axis2=1):") |
| 112 | +print(diag_default) |
| 113 | + |
| 114 | +# Extract diagonal with different axes |
| 115 | +diag_12 = array_3d.diagonal(axis1=1, axis2=2) |
| 116 | +print("\nDiagonal (axis1=1, axis2=2):") |
| 117 | +print(diag_12) |
| 118 | +``` |
| 119 | + |
| 120 | +The output produced by this code is: |
| 121 | + |
| 122 | +```shell |
| 123 | +3D array shape: (2, 3, 3) |
| 124 | +3D array: |
| 125 | +[[[ 1 2 3] |
| 126 | + [ 4 5 6] |
| 127 | + [ 7 8 9]] |
| 128 | + |
| 129 | + [[10 11 12] |
| 130 | + [13 14 15] |
| 131 | + [16 17 18]]] |
| 132 | + |
| 133 | +Diagonal (axis1=0, axis2=1): |
| 134 | +[[ 1 13] |
| 135 | + [ 2 14] |
| 136 | + [ 3 15]] |
| 137 | + |
| 138 | +Diagonal (axis1=1, axis2=2): |
| 139 | +[[ 1 5 9] |
| 140 | + [10 14 18]] |
| 141 | +``` |
| 142 | + |
| 143 | +For 3D arrays, `.diagonal()` extracts diagonal elements from 2D slices defined by the specified axes, resulting in an array with one fewer dimension. |
| 144 | + |
| 145 | +## Codebyte Example |
| 146 | + |
| 147 | +Run the following codebyte example to understand the usage of the `.diagonal()` method: |
| 148 | + |
| 149 | +```codebyte/python |
| 150 | +import numpy as np |
| 151 | +
|
| 152 | +# Create a 4x4 matrix |
| 153 | +matrix = np.array([[1, 2, 3, 4], |
| 154 | + [5, 6, 7, 8], |
| 155 | + [9, 10, 11, 12], |
| 156 | + [13, 14, 15, 16]]) |
| 157 | +print("Original matrix:") |
| 158 | +print(matrix) |
| 159 | +
|
| 160 | +# Extract and display different diagonals |
| 161 | +print("\nMain diagonal:", matrix.diagonal()) |
| 162 | +print("First upper diagonal:", matrix.diagonal(1)) |
| 163 | +print("Second upper diagonal:", matrix.diagonal(2)) |
| 164 | +print("First lower diagonal:", matrix.diagonal(-1)) |
| 165 | +``` |
0 commit comments