有一个可能的解决方案使用stride_tricks
. 这部分基于此问题的答案中可用的大量信息,但我认为,问题只是不同而已,不能算作重复。这是应用于方阵的基本思想——参见下面的实现更通用解决方案的函数。
>>> cols = 8
>>> a = numpy.arange(cols * cols).reshape((cols, cols))
>>> fill = numpy.zeros((cols - 1) * cols, dtype='i8').reshape((cols - 1, cols))
>>> stacked = numpy.vstack((a, fill, a))
>>> major_stride, minor_stride = stacked.strides
>>> strides = major_stride, minor_stride * (cols + 1)
>>> shape = (cols * 2 - 1, cols)
>>> numpy.lib.stride_tricks.as_strided(stacked, shape, strides)
array([[ 0, 9, 18, 27, 36, 45, 54, 63],
[ 8, 17, 26, 35, 44, 53, 62, 0],
[16, 25, 34, 43, 52, 61, 0, 0],
[24, 33, 42, 51, 60, 0, 0, 0],
[32, 41, 50, 59, 0, 0, 0, 0],
[40, 49, 58, 0, 0, 0, 0, 0],
[48, 57, 0, 0, 0, 0, 0, 0],
[56, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 7],
[ 0, 0, 0, 0, 0, 0, 6, 15],
[ 0, 0, 0, 0, 0, 5, 14, 23],
[ 0, 0, 0, 0, 4, 13, 22, 31],
[ 0, 0, 0, 3, 12, 21, 30, 39],
[ 0, 0, 2, 11, 20, 29, 38, 47],
[ 0, 1, 10, 19, 28, 37, 46, 55]])
>>> diags = numpy.lib.stride_tricks.as_strided(stacked, shape, strides)
>>> diags.sum(axis=1)
array([252, 245, 231, 210, 182, 147, 105, 56, 7, 21, 42, 70, 105,
147, 196])
当然,我不知道这实际上会有多快。但我敢打赌,它会比 Python 列表理解更快。
为方便起见,这里有一个完全通用的diagonals
函数。它假设您要沿最长轴移动对角线:
def diagonals(a):
rows, cols = a.shape
if cols > rows:
a = a.T
rows, cols = a.shape
fill = numpy.zeros(((cols - 1), cols), dtype=a.dtype)
stacked = numpy.vstack((a, fill, a))
major_stride, minor_stride = stacked.strides
strides = major_stride, minor_stride * (cols + 1)
shape = (rows + cols - 1, cols)
return numpy.lib.stride_tricks.as_strided(stacked, shape, strides)