2D numpy数组的上对角线

时间:2010-12-14 22:52:42

标签: python numpy slice

这看起来很简单(并且编写三行循环很简单),但是如何使用numpy切片制作numpy数组上对角线的索引位置列表?即。

给定一个4x4数组,我想要X的索引位置:

[ X X X X ]
[ 0 X X X ]
[ 0 0 X X ]
[ 0 0 0 X ]

,并提供:

[ (0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) ]

4 个答案:

答案 0 :(得分:8)

carnieri打败了我numpy.triu_indices的答案,但还有numpy.triu_indices_from以数组作为输入而不是尺寸。

答案 1 :(得分:6)

虽然索引位置的格式不同,但似乎您需要函数numpy.triu_indices

答案 2 :(得分:2)

答案 3 :(得分:2)

如果你正在运行Ubuntu并且不想为此升级Numpy,你可以使用以下功能:

from itertools import chain
triu_indices = lambda x, y=0: zip(*list(chain(*[[(i, j) for j in range(i + y, x)] for i in range(x - y)])))

示例:

In [26]: triu_indices = lambda x, y=0: zip(*list(chain(*[[(i, j) for j in range(i + y, x)] for i in range(x - y)])))

In [27]: triu_indices(4)
Out[27]: [(0, 0, 0, 0, 1, 1, 1, 2, 2, 3), (0, 1, 2, 3, 1, 2, 3, 2, 3, 3)]

In [28]: zip(*triu_indices(4))
Out[28]: 
[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
 (1, 1),
 (1, 2),
 (1, 3),
 (2, 2),
 (2, 3),
 (3, 3)]