Numpy——np.diag()一文看懂
1.np.diag(v, k): 官方文档如下
@array_function_dispatch(_diag_dispatcher)
def diag(v: Union[ndarray, Iterable, int, float],
k: Optional[int] = 0) -> Any
Extract a diagonal or construct a diagonal array.
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.
See Also
diagonal
Return specified diagonals.
diagflat
Create a 2-D array with the flattened input as a diagonal.
trace
Sum along diagonals.
triu
Upper triangle of an array.
tril
Lower triangle of an array.
Examples
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
形参:
v – 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 – Diagonal in question. The default is 0. Use `k>0` for diagonals above the main diagonal, and `k0` for diagonals below the main diagonal.
返回值:
The extracted diagonal or constructed diagonal array.
docs.scipy.org 的 `diag(v, k=0)`
看着很唬人,其实很简单,下面我用通俗的话解释一下。
2.解释:
np.diag(v, k)函数有两种用途
- 返回二维数组v中k相关的对角线数据组成的一维数组
- 返回一个构造的二维与k相关的类对角线形二维数组
2.1 v为一维数组
import numpy as np v = np.array([1, 2, 3, 4, 5]) Z = np.diag(v) print(Z)
输出:
此处k未给定值,为缺省值0.
2.11 k值不为0时
观察可知,k=1时,原主对角线上的数据整体上移1个单位。由此我们可以推出,当k=-1时,原主对角线上的数据整体下移1个单位。
k = -1 时:
2.2 v为二维数组
返回值:默认k=0 返回二维数组主对角线上的数据组成的一维数组
k = 1 时:
返回整体上移1个单位的一维数组
k = -1时:
3.总结
形参:
v–如果“v”是二维数组,则返回其第k条对角线的副本。如果“v”是一个一维数组,则返回一个在“k”对角上有“v”的二维数组。
k–有问题的对角线。默认值为0。对于主对角线上方的对角线,使用“k>0”,对于主对角线下方的对角线,使用“k<0”。
返回值:
提取的对角数组或构造的对角数组。
`diag(v,k=0)`