ImP1
ImP1

Reputation: 49

Slicing a 4-D array in numpy

I created a numpy array called 'd' and then reshape it to get 'd1' as follows:-

d=np.arange(32)
d1=d.reshape(2,2,2,4)

The numpy array 'd1' looks like:-

[[[[ 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 27]
   [28 29 30 31]]]]

I want to slice and extract this array so as to get two 1-D arrays as follows:-

[[13 14]
 [17 18]]

I'm new to numpy and barely started 2 days ago. Am able to do some basic stuff with indexing and slicing. However this one has me stumped for hours. Any help would be much appreciated. Thanks and Regards.

Upvotes: 0

Views: 135

Answers (1)

Ivan
Ivan

Reputation: 40658

If your selection is arbitrary, and you just want a way to get [[13, 14], [17, 18]]. Then, here is a possible solution:

  1. first reshape your nd-array to a 2D array

    >>> d.reshape(8, 4)
    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, 27],
           [28, 29, 30, 31]])
    
  2. slice properly along both remaining axes:

    >>> d.reshape(8, 4)[3:5, 1:3]
    array([[13, 14],
           [17, 18]])
    

Alternatively you can always unravel the indices into d shape and index the array with those:

>>> idx = np.unravel_index([13, 14, 17, 18], d.shape)
(array([0, 0, 1, 1]),
 array([1, 1, 0, 0]),
 array([1, 1, 0, 0]),
 array([1, 2, 1, 2]))

>>> d[idx]
array([13, 14, 17, 18])

Upvotes: 1

Related Questions