Reputation: 117
From a numpy array
a=np.arange(100).reshape(10,10)
I want to obtain an array
[[99, 90, 91],
[9, 0, 1],
[19, 10, 11]]
I tried
a[[-1,0,1],[-1,0,1]]
but this instead gives array([99, 0, 11])
. How can I solve this problem?
Upvotes: 1
Views: 56
Reputation: 3824
Split the slicing into two seperate operations
arr[ [ -1,0,1] ][ :, [ -1,0,1]]
# array([[99., 90., 91.],
# [ 9., 0., 1.],
# [19., 10., 11.]])
Equivalent to:
temp = arr[ [ -1,0,1] ] # Extract the rows
temp[ :, [ -1,0,1]] # Extract the columns from those rows
# array([[99., 90., 91.],
# [ 9., 0., 1.],
# [19., 10., 11.]])
Upvotes: 1
Reputation: 120391
Roll your array over two axis and slice 3x3:
>>> np.roll(a, shift=1, axis=[0,1])[:3, :3]
array([[99, 90, 91],
[ 9, 0, 1],
[19, 10, 11]])
Upvotes: 2
Reputation: 21
a[[-1,0,1],[-1,0,1]]
This is wrong, this means you want an elements from row -1
, column -1
i.e (99)
and row 0
, column 0
i.e (0)
and row 1
, column 1
i.e (11)
this is the reason you are getting array([99, 0, 11])
Your Answer:
a[ [[-1],[0],[1]], [-1,0,1] ]
: This means, we want every element from column -1, 0, 1
from row [-1], [0], [1]
.
Upvotes: 1