NumPy参考 >例行程序 >Indexing routines > numpy.fill_diagonal
numpy.
fill_diagonal
(a,val,wrap = False )[源代码] ¶填充任意维度的给定数组的主对角线。
用于阵列一个与,对角线是具有索引位置列表全部相同。此函数就地修改输入数组,但不返回值。a.ndim >= 2
a[i, ..., i]
要填充对角线的数组,将对其进行就地修改。
要写在对角线上的值,其类型必须与数组a的类型兼容。
对于NumPy版本高达1.6.2的高矩阵,对角线在N列后“包裹”。使用此选项,您可以具有这种行为。这仅影响高矩阵。
也可以看看
笔记
1.4.0版的新功能。
可以通过获得此功能diag_indices
,但是在内部,此版本使用更快的实现,该实现从不构造索引并且使用简单的切片。
例子
>>> a = np.zeros((3, 3), int)
>>> np.fill_diagonal(a, 5)
>>> a
array([[5, 0, 0],
[0, 5, 0],
[0, 0, 5]])
相同的功能可以在4-D阵列上运行:
>>> a = np.zeros((3, 3, 3, 3), int)
>>> np.fill_diagonal(a, 4)
为了清楚起见,我们仅显示几个块:
>>> a[0, 0]
array([[4, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a[1, 1]
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 0]])
>>> a[2, 2]
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 4]])
wrap选项仅影响高矩阵:
>>> # tall matrices no wrap
>>> a = np.zeros((5, 3), int)
>>> np.fill_diagonal(a, 4)
>>> a
array([[4, 0, 0],
[0, 4, 0],
[0, 0, 4],
[0, 0, 0],
[0, 0, 0]])
>>> # tall matrices wrap
>>> a = np.zeros((5, 3), int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0],
[0, 4, 0],
[0, 0, 4],
[0, 0, 0],
[4, 0, 0]])
>>> # wide matrices
>>> a = np.zeros((3, 5), int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0, 0, 0],
[0, 4, 0, 0, 0],
[0, 0, 4, 0, 0]])
可以通过使用numpy.flipud
或反转元素的顺序来填充反对角线numpy.fliplr
。
>>> a = np.zeros((3, 3), int);
>>> np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip
>>> a
array([[0, 0, 1],
[0, 2, 0],
[3, 0, 0]])
>>> np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip
>>> a
array([[0, 0, 3],
[0, 2, 0],
[1, 0, 0]])
请注意,对角线的填充顺序取决于翻转功能。