假设有一个3行3列的numpy矩阵。找到第一个对角线很容易,这是一个方法。
以下是示例矩阵:
[[0,3,6]
[0,4,9]
[0,1,9]]
使用以下代码:
import numpy
matrix.diagonals()
[0, 4, 9]
如何获得对角线的相反方向?例如,对于上面的矩阵,我希望它返回:
[6, 4, 0]
实现这一目标最快的方法是使用步幅。您的数组具有一个.strides
属性,该属性告诉您在每个维度中要跳过多少字节才能到达下一个项目:
>>> a = np.array([[0, 3, 6], [0, 4, 9], [0, 1, 9]])
>>> a.strides
(24, 8)
正斜线需要跳过一行加一列,反斜线需要跳过一行减一列:
>>> a.strides[0] + a.strides[1]
32
>>> a.strides[0] - a.strides[1]
16
>>> np.ndarray(shape=min(a.shape), dtype=a.dtype, buffer=a,
... offset=0, strides=a.strides[0]+a.strides[1])
array([0, 4, 9])
>>> np.ndarray(shape=min(a.shape), dtype=a.dtype, buffer=a,
... offset=a.strides[1] * (a.shape[1] - 1),
... strides=a.strides[0]+a.strides[1])
array([6, 4, 0])
实际上,这些是对原数组内存的视图。也就是说,如果您修改它们的内容,原始数组也会发生更改。因此,几乎没有进行任何内存分配或复制,只需设置包含对象,所以它将非常快速。
In [29]: mm
Out[29]:
matrix([[0, 3, 6],
[0, 4, 9],
[0, 1, 9]])
In [30]: np.fliplr(mm)
Out[30]:
matrix([[6, 3, 0],
[9, 4, 0],
[9, 1, 0]])
In [31]: mm.diagonal()
Out[31]: matrix([[0, 4, 9]])
In [33]: np.fliplr(mm).diagonal()
Out[33]: matrix([[6, 4, 0]])
import numpy
a = numpy.matrix([[0, 3, 6], [0, 4, 9], [0, 1, 9]])
print(numpy.diag(a))
print(numpy.diag(a[::-1])[::-1])
output:
[0 4 9]
[6 4 0]
In [240]: M=np.arange(9).reshape(3,3)
M[i,j]当i==j
,我们可以使用相同的数组进行高级索引以获取i和j的值。In [241]: i=np.arange(3)
In [242]: M[i,i]
Out[242]: array([0, 4, 8])
In [243]: M[i,i[::-1]]
Out[243]: array([2, 4, 6])
===========
糟糕,我错了。 M.diagonal()
比我的显式索引快得多。对于 N=1000
。
In [259]: timeit M.diagonal();np.fliplr(M).diagonal()
100000 loops, best of 3: 3.63 µs per loop
In [260]: timeit i=np.arange(N);mm=M[i,i],M[i,i[::-1]]
10000 loops, best of 3: 51.3 µs per loop