1

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?

1
  • its called numpy slicing... just google it you will find everything you need to know. To answer your question quickly you probably want to something like a[3:7,5:9] Commented Jul 2, 2021 at 11:25

3 Answers 3

2

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]])
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.