Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slices along arbitrary axis

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.

like image 454
Johan Råde Avatar asked Sep 05 '12 07:09

Johan Råde


1 Answers

# 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)]]
like image 125
Nicolas Barbey Avatar answered Sep 18 '22 11:09

Nicolas Barbey