numpy.triu_indices#

numpy.triu_indices(n, k=0, m=None)[源代码]#

返回一个 (n, m) 数组的上三角的索引.

参数:
nint

返回的索引有效的数组的大小.

k整数,可选

对角线偏移量(有关详细信息,请参见 triu ).

m整数,可选

返回的数组对其有效的数组的列维度.默认情况下, m 等于 n .

返回:
inds : tuple, shape(2) of ndarrays, shape( n )tuple, shape(2) of ndarrays, shape(n)

行和列的索引,分别.行索引以非递减顺序排序,并且对于每一行,对应的列索引严格递增.

参见

tril_indices

类似的函数,用于下三角.

mask_indices

接受任意掩码函数的通用函数.

triu , tril

示例

>>> import numpy as np

计算两组不同的索引以访问 4x4 数组,一组用于从主对角线开始的上三角部分,一组从右侧两个对角线开始:

>>> iu1 = np.triu_indices(4)
>>> iu1
(array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 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[iu1]
array([ 0,  1,  2, ..., 10, 11, 15])

以及用于赋值:

>>> a[iu1] = -1
>>> a
array([[-1, -1, -1, -1],
       [ 4, -1, -1, -1],
       [ 8,  9, -1, -1],
       [12, 13, 14, -1]])

这些只覆盖了整个数组的一小部分(主对角线右边的两个对角线):

>>> iu2 = np.triu_indices(4, 2)
>>> a[iu2] = -10
>>> a
array([[ -1,  -1, -10, -10],
       [  4,  -1,  -1, -10],
       [  8,   9,  -1,  -1],
       [ 12,  13,  14,  -1]])