I have a numpy array A
such that
A.shape[axis] = n+1.
Now I want to construct two slices B
and C
of A
by selecting the indices 0, .., n-1
and 1, ..., n
respectively along the axis axis
. Thus
B.shape[axis] = C.shape[axis] = n
and B
and C
have the same size as A
along the other axes. There must be no copying of data.
# 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]
One-liners :
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)]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With