0

In this example:

In [19]: a[[1,2,3],[1,2,3]].shape
Out[19]: (3,)

In [20]: a[1:4,1:4].shape
Out[20]: (3, 3)

In [21]: a.shape
Out[21]: (100, 100)

Why Out[19] is not (3,3)? The reason that I want to use list is because I want to do something like this:

a[[1,8,12],[34,45,50]].shape

So that the result would be a (3,3) matrix.

2
  • I believe what you want to do with fancy indexing here only works with range objects, not arrays of individual row/column indices. Commented May 1, 2018 at 15:31
  • Your a[<list>,<list>] attempts will do a zip-like operation, where your resulting array will be [a[1,1], a[2,2], a[3,3]] -- this is why it's not 3x3 but 3x1. Commented May 1, 2018 at 15:35

1 Answer 1

4

Perfect use case for np.ix_:

a[np.ix_([1,8,12],[34,45,50])]

Demo

a = np.arange(5 * 5).reshape(5, 5)    
a[np.ix_([1, 2, 3], [1, 2, 3])]

array([[ 6,  7,  8],
       [11, 12, 13],
       [16, 17, 18]])
Sign up to request clarification or add additional context in comments.

1 Comment

And more efficient than a[[1,2,3],:][:,[1,2,3]]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.