Chris Uchytil
Chris Uchytil

Reputation: 150

Arbitary 1D slices (elements along an axis) across an ndarray - NumPy

There are a few questions I've found that are close to what I am asking but they are different enough that they don't seem to solve my problem. I am trying to grab a 1d slice along one axis for an ndarray. As an example for a 3d 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]]]

I want the following 1d slices

[0,1,2]
...
[24,25,26]

[0,3,6]
...
[20,23,26]

[0,9,18]
...
[8,17,26]

which effectively equates to the following (for a 3d arrays):

ary[i,j,:]
ary[i,:,k]
ary[:,j,k]

I want this to generalize to an array of n dimensions

(for a 2d array we would get ary[i,:] and ary[:,j], etc.)

Is there a numpy function that lets me do this?

EDIT: Corrected the 2nd dimension indexing

Upvotes: 1

Views: 91

Answers (1)

Divakar
Divakar

Reputation: 221614

We could permute axes by selecting each one of the axes one at a time pushing it at the end and reshape. We would make use of ndarray.ndim to generalize to generic n-dim ndarrays. Also, np.transpose would be useful here to permute axes and np.roll to get rolled axes order. The implementation would be quite simple and is listed below -

# a is input ndarray
R = np.arange(a.ndim)
out = [np.transpose(a,np.roll(R,i)).reshape(-1,a.shape[i]) for i in R]

Sample run -

In [403]: a = np.arange(27).reshape(3,3,3)

In [325]: R = np.arange(a.ndim)

In [326]: out = [np.transpose(a,np.roll(R,i)).reshape(-1,a.shape[i]) for i in R]

In [327]: out[0]
Out[327]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       ...
       [24, 25, 26]])

In [328]: out[1]
Out[328]: 
array([[ 0,  3,  6],
       [ 9, 12, 15],
       ....
       [20, 23, 26]])

In [329]: out[2]
Out[329]: 
array([[ 0,  9, 18],
       [ 1, 10, 19],
       ....
       [ 8, 17, 26]])

Upvotes: 1

Related Questions