[Numpy-discussion] Getting an item in an array with its coordinates given by another array

Travis E. Oliphant oliphant@enthought....
Mon Oct 29 11:57:23 CDT 2007


Matthieu Brucher wrote:
> Hi,
>
> I'm trying to get an item in an array when I only have another array 
> giving the position.
>
> For instance:
>
> >>> c = numpy.arange(0., 3*4*5).reshape((3,4,5))
> >>> c***(numpy.array ((2,3), dtype=int))
> [55, 56, 57, 58, 59]
>
> I'm trying to figure what to put between c and ((2,3)). I supposed 
> that the take method would be what I wanted but it is not... The [] 
> operator does not work on array(but it seems to give the expected 
> result with a tuple or a list). Is there a method for this ?

What do you mean by "item" in an array?  Usually, when I refer to an 
"item" in the array, I'm talking about getting a particular element of 
the array. 

It would appear that you are trying to get a "sub-array" or "sub-space" 
of the array because you are using partial indexing. 

Getting a particular sub-array is the easiest thing to do with NumPy and 
only requires something like

c[2,3]

Presumably, you are trying to create the numbers on the fly and so want 
to know what to create.   The answer is that you should create a tuple 
of the numbers because as others have mentioned:

c[2,3] is equivalent to c[(2,3)] on the interpreter level (i.e. the 
numpy array cannot tell the difference between the two forms of syntax).

Almost all of the time a list is interpreted as "advanced indexing" 
(because there needed to be some way to distinguish the two).  I say 
"almost" because there is one exception to the rule that occurs if your 
list has less than or equal to the same number of elements as the number 
of dimensions of the array *and* contains slice objects, or Ellipsis, or 
newaxis.  In that case, the list will be interpreted as a tuple.

Thus, in your case you could do

c[[2,3,slice(None)]]  or
c[[2,3,Ellipsis]]

and get your desired result.   This (in my view) less than ideal 
behavior was created for backward compatibility to a pattern that had 
emerged for constructing indexing objects for multi-dimensional slicing.  

I'm pretty sure that numpy arrays of type integer are *always* 
interpreted as fancy indexing.

Let me know if there is more clarification needed.   The relevant code 
is in the function fancy_indexing_check in arrayobject.c of the source code.

Best regards,

-Travis O.


-Travis







>
> Matthieu
>
> -- 
> French PhD student
> Website : http://miles.developpez.com/
> Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
> ------------------------------------------------------------------------
>
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>   



More information about the Numpy-discussion mailing list