How to slice range of array along a (a-priori unknown) axis?
Peter Otten
__peter__ at web.de
Thu Feb 5 05:58:15 EST 2004
Maarten van Reeuwijk wrote:
> I am using the Numeric package, and I need to strip edge cells off an
> array (dimension unknown) in an a-priori unknown direction. I implented
> this as follows:
>
> def el_remove_bcells(var, axis):
> """ elementary routine to strip the edge cells of an array for the
> given
> direction.
> """
>
> if axis == 0:
> return var[1:-1]
> if axis == 1:
> return var[:, 1:-1]
> else:
> return var[:, :,1:-1]
>
> But this only works for at most 3D arrays. It must be possible to program
> this fragment without the ifs, for arrays of arbitrary dimension. Is there
> a command in the Numerical package I can use for this? It is very
> important that this method is very fast, as my arrays normally are in the
> order of 100 Mb.
Maybe:
>>> def clipdim(a, n):
... t = [slice(None)] * N.rank(a)
... t[n] = slice(1,-1)
... return a[t]
...
>>> a
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
>>> clipdim(a, 0)
array([ [[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]])
>>> clipdim(a, 1)
array([[ [ 3, 4, 5]],
[ [12, 13, 14]],
[ [21, 22, 23]]])
>>> clipdim(a, 2)
array([[[ 1],
[ 4],
[ 7]],
[[10],
[13],
[16]],
[[19],
[22],
[25]]])
Peter
More information about the Python-list
mailing list