Home > Mobile >  Numpy slicing with index
Numpy slicing with index

Time:04-12

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]])

Can I do this thing in an elegant way? Of course, the above code induces a type error "TypeError: only integer scalar arrays can be converted to a scalar index". Thanks

CodePudding user response:

Here's how I went about figuring out a solution:

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]])

Looks like you want several 'diagonals', which we can get with pairs of indexing 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])

Put those together into index:

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

And generate that 2d indexing array:

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]])

CodePudding user response:

Okay, it's not elegant, but it works.

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

Output:

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