NumPy | fill_diagonal method
Start your free 7-days trial now!
Numpy's fill_diagonal(~)
method sets a specified value for the diagonals of the Numpy array. Note that this happens in-place, that is, no new array is created.
Parameters
1. a
| array-like
The input array.
2. val
link | scalar
The desired value to fill the diagonals.
3. wrap
link | boolean
| optional
For 2D arrays that have more rows than columns (i.e. tall matrices), then we can repeatedly fill diagonals. See examples for clarification. By default, wrap=False
.
Return value
None - diagonals are filled in-place.
Examples
Basic usage
Consider the following 2D array:
a = np.array([[5,6],[7,8]])a
array([[5, 6], [7, 8]])
To fill the diagonals with the value 2:
np.fill_diagonal(a, 2)a
array([[2, 6], [7, 2]])
Tall matrices
Consider the following tall 2D array:
a = np.array([[1,1],[1,1],[1,1],[1,1],[1,1]])a
array([[1, 1], [1, 1], [1, 1], [1, 1], [1, 1]])
Without wrapping
By default, there is no wrapping behaviour, and so only the main diagonal will be filled:
np.fill_diagonal(a, 0)a
array([[0, 1], [1, 0], [1, 1], [1, 1], [1, 1]])
With wrapping
To enable the wrapping behaviour, set wrap=True
like so:
np.fill_diagonal(a, 0, wrap=True)a
array([[0, 1], [1, 0], [1, 1], [0, 1], [1, 0]])
Notice how a single row is skipped before the next diagonals are filled.