This is a pre-release version (2.5.0.dev0+git20251130.2de293a). Go to latest (2.4.4)
{ } Raw JSON

bundles / numpy 2.5.0.dev0+git20251130.2de293a / numpy / diag

_ArrayFunctionDispatcher

numpy:diag

source: /dev/numpy/build-install/usr/lib/python3.14/site-packages/numpy/lib/_twodim_base_impl.py :258

Signature

def   diag ( v k = 0 )

Summary

Extract a diagonal or construct a diagonal array.

Extended Summary

See the more detailed documentation for numpy.diagonal if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using.

Parameters

v : array_like

If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal.

k : int, optional

Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal.

Returns

out : ndarray

The extracted diagonal or constructed diagonal array.

Examples

import numpy as np
x = np.arange(9).reshape((3,3))
x
np.diag(x)
np.diag(x, k=1)
np.diag(x, k=-1)
np.diag(np.diag(x))

See also

diagflat

Create a 2-D array with the flattened input as a diagonal.

diagonal

Return specified diagonals.

trace

Sum along diagonals.

tril

Lower triangle of an array.

triu

Upper triangle of an array.

Aliases

  • numpy.diag

Referenced by