[Numpy-discussion] On responding to dubious ideas (was: Re: Advanced indexing: "fancy" vs. orthogonal)

Alexander Belopolsky ndarray at mac.com
Thu Apr 9 20:23:44 EDT 2015


On Thu, Apr 9, 2015 at 12:12 PM, <josef.pktd at gmail.com> wrote:

> On Thu, Apr 9, 2015 at 10:11 AM, Alan G Isaac <alan.isaac at gmail.com>
> wrote:
> >  > Alan wrote:
> >>> 3. I admit, my students are NOT using non-boolen fancy indexing on
> >>> >multidimensional arrays. (As far as I know.)  Are yours?
>
> The only confusing case is mixing slices and integer array indexing
> for ndim > 2. The rest looks unsurprising, AFAIR


What I find somewhat annoying is the difficulty of simultaneously selecting
 a subset of rows and columns from a given matrix.

Suppose I have

>>> a
array([[11, 12, 13, 14],
       [21, 22, 23, 24],
       [31, 32, 33, 34],
       [41, 42, 43, 44]])

If I want to select the first two rows and first two columns, I do

>>> a[:2,:2]
array([[11, 12],
       [21, 22]])

If I want rows 1 and 2 or columns 1 and 2, it is easy and natural

>>> a[[1,2]]
array([[21, 22, 23, 24],
       [31, 32, 33, 34]])

>>> a[:,[1,2]]
array([[12, 13],
       [22, 23],
       [32, 33],
       [42, 43]])

but if I try to do both, I get the diagonal instead

>>> a[[1,2],[1,2]]
array([22, 33])

I could do

>>> a[[1,2]][:,[1,2]]
array([[22, 23],
       [32, 33]])

but this creates an extra copy.

The best solution I can think of involves something like

>>> i = np.array([[1,2]])
>>> a.flat[i + len(a)*i.T]
array([[22, 23],
       [32, 33]])

which is hardly elegant or obvious.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20150409/6fdd66c5/attachment.html>


More information about the NumPy-Discussion mailing list