[Numpy-discussion] Two questions on indexing

Brett Olsen brett.olsen at gmail.com
Wed Sep 15 17:49:57 EDT 2010


On Wed, Sep 15, 2010 at 4:38 PM, Mark Fenner <mfenner at gmail.com> wrote:
> A separate question.  Suppose I have a slice for indexing that looks like:
>
> [:, :, 2, :, 5]
>
> How can I get an indexing slice for all OTHER dimension values besides
> those specified.  Conceptually, something like:
>
> [:, :, all but 2, :, all but 5]
>
> Incidentally, the goal is to construct a new array with all those
> "other" spots filled in with zero and the specified spots with their
> original values.  Would it be easier to construct a 0-1 indicator
> array with 1s in the [:,:,2,:,5] positions and multiply it out?  Humm,
> I may have just answered my own question.
>
> For argument sake, how would you do it with indexing/slicing?  I
> suppose one develops some intuition as one gains experience with numpy
> with regards to when to (1) use clever matrix ops and when to (2) use
> clever slicing and when to (3) use a combination of both.

This works, although I'm not sure how efficient it is compared to other methods:

In [19]: a = N.arange(16).reshape(4,4)
In [20]: a
Out[20]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

In [24]: a[:,N.arange(4) != 2]
Out[24]:
array([[ 0,  1,  3],
       [ 4,  5,  7],
       [ 8,  9, 11],
       [12, 13, 15]])

Brett



More information about the NumPy-Discussion mailing list