[Numpy-discussion] Two questions on indexing

Mark Fenner mfenner@gmail....
Wed Sep 15 16:38:49 CDT 2010

One method of using indices seems to be as follows:

In [19]: a = N.array(range(6)).reshape(3,2)
In [20]: i = N.indices([3,2])
In [21]: r,c = i
In [22]: a[r,c]
array([[0, 1],
      [2, 3],
      [4, 5]])

In [23]: a[tuple(i)]
array([[0, 1],
      [2, 3],
      [4, 5]])

*****Question 1:*****

For using the results of argmax, how would one "pad" the indices
returned by argmax to be usable as follows (note, I resorted to method
I found on numpy-discussion ... google "take_axis" ... that revolves
around rolling the desired axis to the first position and then using
the indices ... I'm curious how to make something like what I have
below work).  Incidentally, the number of  dimensions can be arbitrary
(for my needs):

x = N.array([[2, 3],
                [1, 5]])

for a in [0, 1]:
    indices = N.argmax(x, axis=a)

    # perhaps something similar to the following?
    # grid = N.indices(x.shape)
    # grid[a] = indices # <--- this is the idea, but it fails to get
the necessary result
    # usable = tuple(grid)

    assert x[usableIndices] == x.max(axis=a) # or similar

*****Question 2:*****

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.


More information about the NumPy-Discussion mailing list