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?
a[[-1,0,1],[-1,0,1]]
This is wrong, this means you want an elements from row -1
, column -1
ie (99)
and row 0
, column 0
ie (0)
and row 1
, column 1
ie (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]
.
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]])
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.]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.