原文:https://docs.scipy.org/doc/numpy/reference/generated/numpy.diag_indices.html
校对:(虚位以待)
numpy.
diag_indices
(n, ndim=2)[source]返回索引以访问数组的主对角线。
这返回可用于访问数组a的主对角线的索引的元组,其中a.ndim > = 2
尺寸和形状(n,n,...,n)。For a.ndim = 2
this is the usual diagonal, for a.ndim > 2
this is the set of indices to access a[i, i, ..., i]
for i = [0..n-1]
.
参数: | n:int
ndim:int,可选
|
---|
也可以看看
笔记
版本1.4.0中的新功能。
例子
创建一组索引以访问(4,4)数组的对角线:
>>> di = np.diag_indices(4)
>>> di
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> a[di] = 100
>>> a
array([[100, 1, 2, 3],
[ 4, 100, 6, 7],
[ 8, 9, 100, 11],
[ 12, 13, 14, 100]])
现在,我们创建索引来操纵3-D数组:
>>> d3 = np.diag_indices(2, 3)
>>> d3
(array([0, 1]), array([0, 1]), array([0, 1]))
并使用它将零的数组的对角线设置为1:
>>> a = np.zeros((2, 2, 2), dtype=np.int)
>>> a[d3] = 1
>>> a
array([[[1, 0],
[0, 0]],
[[0, 0],
[0, 1]]])