Slices along an arbitrary axis

I have a numpy array Asuch that

A.shape[axis] = n+1.

Now I want to build two slices Band Cof A, choosing indexes 0, .., n-1and 1, ..., nrespectively along the axis axis. In this way,

B.shape[axis] = C.shape[axis] = n

and Band Chave the same size as Aalong other axes. There should be no data copying.

+5
source share
1 answer
# exemple data
A = np.random.rand(2, 3, 4, 5)
axis = 2
n = A.ndim
# building n-dimensional slice
s = [slice(None), ] * n
s[axis] = slice(0, n - 1)
B = A[s]
s[axis] = slice(1, n)
C = A[s]

Single line:

B = A[[slice(None) if i != axis else slice(0, n-1) for i in xrange(n)]]
C = A[[slice(None) if i != axis else slice(1, n) for i in xrange(n)]]
+8
source

All Articles