How to dynamically access Numeric subarrays
Christopher T King
squirrel at WPI.EDU
Tue Aug 3 09:43:40 EDT 2004
On Tue, 3 Aug 2004, Gaubitzer Erwin wrote:
> So my questions to out there:
> How can I extract a (Numeric Python) subarray whose indices
> have to be built dynamically.
The Numeric function take() might meet your needs:
>>> from Numeric import *
>>> a = array([[[1,2],[3,4]],[[5,6],[7,8]]])
>>> take(a,(0,),0)
array([ [[1, 2],
[3, 4]]])
>>> take(a,(1,),0)
array([ [[5, 6],
[7, 8]]])
>>> take(a,(0,),1)
array([[ [1, 2]],
[ [5, 6]]])
>>> take(a,(0,),2)
array([[[1],
[3]],
[[5],
[7]]])
The second argument specifies which indices to take, and the third
argument specifies to which dimension to apply the indices.
Note that take() returns an array of the same rank as that of its input;
this may not be what you want. To obtain an array of one less dimension,
you'll need to reshape it. A function like the following may be helpful:
def takeslice(a,index,dimension):
r = take(a,(index,),dimension)
s = shape(r)
return reshape(r,s[:dimension]+s[dimension+1:])
This will only accept single indexes to slice, rather than a tuple, but
will return you an array of rank N-1 from that which it is passed:
>>> takeslice(a,0,0)
array([[1, 2],
[3, 4]])
>>> takeslice(a,1,0)
array([[5, 6],
[7, 8]])
>>> takeslice(a,0,1)
array([[1, 2],
[5, 6]])
>>> takeslice(a,0,2)
array([[1, 3],
[5, 7]])
Also of tangential interest is the ... operator. This magic operator,
given to a slice, means "replace me with however many : are needed to make
this work". It won't necessarily help your situation, but it's a handy
thing to know:
>>> a[0,...]
array([[1, 2],
[3, 4]])
>>> a[1,...]
array([[5, 6],
[7, 8]])
>>> a[...,0]
array([[1, 3],
[5, 7]])
Hope this helps, and is understandable :)
More information about the Python-list
mailing list