0

Say if I have a 2D array:

y = np.arange(35).reshape(5,7)
# array([[ 0,  1,  2,  3,  4,  5,  6],
#        [ 7,  8,  9, 10, 11, 12, 13],
#        [14, 15, 16, 17, 18, 19, 20],
#        [21, 22, 23, 24, 25, 26, 27],
#        [28, 29, 30, 31, 32, 33, 34]])

and select the 2nd and 3rd elements of the 1st, 3rd and 5th array like so:

y[np.array([0,2,4]), 1:3]
# array([[ 1,  2],
#        [15, 16],
#        [29, 30]])

I cannot find a way to replicate this using arrays in place of the slice for indexing, the following doesn't work, I must be able to use arrays to index as I sometimes might be interested in the 2nd and 4th elements of the arrays and so on:

y[np.array([0,2,4]), np.array([1,2])]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,)

How can I achieve my desired functionality?

5
  • You need to use a list, just as you did with the first dimension. Commented Apr 6, 2020 at 20:04
  • As you can see, that doesn't work, the indexing arrays could not be broadcast together Commented Apr 6, 2020 at 20:04
  • I see where you use a list and an array; I do not see where you've used two lists. Commented Apr 6, 2020 at 20:06
  • Do you mind giving an example of what you mean, I am not sure I follow? Commented Apr 6, 2020 at 20:07
  • broadcasting with indices is the same as with addition or multiplication. np.array([1,2])[:,None] + np.array([1,2,3]) produces a (2,3) sum. arr[np.array([1,2])[:,None], np.array([1,2,3])] indexes a (2,3) block. Commented Apr 6, 2020 at 20:33

4 Answers 4

2

np.ix_() is designed for this type of problem.

def getSub():
    y = np.arange(35).reshape(5,7)
    locs = np.ix_([0,2,4],[1,2])
    return y[locs]


>>> getSub()
array([[ 1,  2],
       [15, 16],
       [29, 30]])
Sign up to request clarification or add additional context in comments.

Comments

0

y[np.array([0,2,4]), np.array([[1],[2]])].T

Comments

0

you can try to use this y[np.array([[0,2,4]]*2),np.array([[1]*3,[2]*3])].T

Comments

0

Quick, dirty way to achieve it with double indexing.

y[np.array([0,2,4]),:][:,np.array([1,2])]

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.