The standard rules of Python slicing apply to arrays, on a per-dimension basis. Assuming a 3x3 array:
>>> a = reshape(arange(9),(3,3)) >>> print a [[0 1 2] [3 4 5] [6 7 8]]
[:]
operator slices from beginning to end:
>>> print a[:,:] [[0 1 2] [3 4 5] [6 7 8]]
[:]
with no arguments is the same as [:]
for
lists -- it can be read ``all indices along this axis''. (Actually, there is
an important distinction; see below.) So, to get the second row along the
second dimension:
>>> print a[:,1] [1 4 7]
>>> a = arange (20) >>> b = a[3:8] >>> c = a[3:8].copy() >>> a[5] = -99 >>> print b [ 3 4 -99 6 7] >>> print c [3 4 5 6 7]
A[1] == A[1,:] == A[1,:,:]
>>> a = arange(12) >>> print a [ 0 1 2 3 4 5 6 7 8 9 10 11] >>> print a[::2] # return every *other* element [ 0 2 4 6 8 10]
>>> a = reshape(arange(9),(3,3)) Array Basics >>> print a [[0 1 2] [3 4 5] [6 7 8]] >>> print a[:, 0] [0 3 6] >>> print a[0:3, 0] [0 3 6] >>> print a[2::-1, 0] [6 3 0]
>>> print a[2::-1, 0] [6 3 0] >>> print a[::-1, 0] [6 3 0] >>> print a[::-1] # this reverses only the first axis [[6 7 8] [3 4 5] [0 1 2]] >>> print a[::-1,::-1] # this reverses both axes [[8 7 6] [5 4 3] [2 1 0]]
So, if one has a rank-3 array A, then A[...,0]
is the same thing
as A[:,:,0]
, but if B is rank-4, then B[...,0]
is the same
thing as: B[:,:,:,0]
. Only one "..." is expanded in an index
expression, so if one has a rank-5 array C, then C[...,0,...]
is
the same thing as C[:,:,:,0,:]
.
Note that the result of assigning a slice of an array to an overlapping slice of the same array is undefined:
>>> a[1:,1:] = a[:2, :2] # don't do this! undefined
Send comments to the NumArray community.