1

Say x is a 3x3 numpy array that contains the following:

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

is there some indexing that can give me the following subarray:

array([[ 1.,  2.],
       [ 5.,  6.]])
2
  • 1
    Have you tried anything? Commented Feb 4, 2017 at 4:15
  • Yes things like x[(0,2), 0:2] but to no avail. I could not get subsets like the one i mentioned. Commented Feb 4, 2017 at 4:38

2 Answers 2

4

You can use integer array indexing with a tuple of arrays:

>>> rows = np.array([[0, 0],
...                  [1, 1]], dtype=np.intp)
>>> columns = np.array([[0, 1],
...                     [1, 2]], dtype=np.intp)
>>> x[rows, columns]
array([[ 1.,  2.],
       [ 5.,  6.]])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, actually based on your suggestion the following also seems to work (I'm looking for a one-liner): x[[[0, 0],[1, 1]], [[0, 1],[1, 2]]]
okay, I wasn't aware you were looking for short code so I chose to show the explicit one. It is a bit clearer what the rows represents and what the columns are. :)
-3

you can use

x[:2,:2]

to solve your problem

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.