larray.diag

larray.diag(a, k=0, axes=(0, 1), ndim=2, split=True) Array[source]

Extract a diagonal or construct a diagonal array.

Parameters
aArray

If a has 2 dimensions or more, return a copy of its k-th diagonal. If a has 1 dimension, return an array with ndim dimensions on the k-th diagonal.

kint, optional

Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0).

axestuple or list or AxisCollection of axes references, optional

Axes along which the diagonals should be taken. Use None for all axes. Defaults to the first two axes (0, 1).

ndimint, optional

Target number of dimensions when constructing a diagonal array from an array without axes names/labels. Defaults to 2.

splitbool, optional

Whether to try to split the axis name and labels. Defaults to True.

Returns
Array

The extracted diagonal or constructed diagonal array.

Examples

>>> nat = Axis('nat=BE,FO')
>>> sex = Axis('sex=M,F')
>>> a = ndtest([nat, sex], start=1)
>>> a
nat\sex  M  F
     BE  1  2
     FO  3  4
>>> d = diag(a)
>>> d
nat_sex  BE_M  FO_F
            1     4
>>> diag(d)
nat\sex  M  F
     BE  1  0
     FO  0  4
>>> a = ndtest(sex, start=1)
>>> a
sex  M  F
     1  2
>>> diag(a)
sex\sex  M  F
      M  1  0
      F  0  2