带有索引的 Numpy 切片

Numpy slicing with index

x = np.array([
[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]
])

end_point =  [3, 4]    # Slicing end point

# Want: Slicing along the row, like this
x[end_point-2 : end_point] 
=  np.array([[2, 5], [4, 7], [6, 9]])

我可以优雅地做这件事吗?当然,上面的代码会导致类型错误 “类型错误:只能将整数标量数组转换为标量索引”。谢谢

以下是我找出解决方案的方法:

In [21]: x = np.arange(10).reshape(5,2)
In [22]: x
Out[22]: 
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])

看起来你想要几个 'diagonals',我们可以用成对的索引 lists/arrays:

In [23]: x[[1,2],[0,1]]
Out[23]: array([2, 5])
In [24]: x[[2,3],[0,1]]
Out[24]: array([4, 7])
In [25]: x[[3,4],[0,1]]
Out[25]: array([6, 9])

将它们一起放入索引中:

In [26]: x[[[1,2],[2,3],[3,4]],[0,1]]
Out[26]: 
array([[2, 5],
       [4, 7],
       [6, 9]])

并生成二维索引数组:

In [28]: np.arange(1,4)[:,None]+[0,1]
Out[28]: 
array([[1, 2],
       [2, 3],
       [3, 4]])
In [29]: idx = np.arange(1,4)[:,None]+[0,1]
In [30]: x[idx,np.arange(2)]
Out[30]: 
array([[2, 5],
       [4, 7],
       [6, 9]])

好吧,它并不优雅,但它确实有效。

x = np.array([
[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]
])
end_point = np.array([3, 4])
L = np.array([row[t-2:t+1] for row,t in zip(x.T, end_point)]).T

输出:

[[2 5]
 [4 7]
 [6 9]]