search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# NumPy | fill_diagonal method

schedule Aug 11, 2023
Last updated
local_offer
PythonNumPy
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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.

Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!