w3resource

Select a Subarray from 4D NumPy array using Multi-dimensional indexing


4. 4D Array & Multi-dimensional Indexing

Multi-dimensional Indexing:

Write a NumPy program that creates a 4D NumPy array and uses multi-dimensional indexing to select a subarray.

Sample Solution:

Python Code:

import numpy as np

# Create a 4D NumPy array of shape (3, 4, 5, 6) with random integers
array_4d = np.random.randint(0, 100, size=(3, 4, 5, 6))

# Use multi-dimensional indexing to select a subarray
# For example, select all elements from the first two blocks, 
# first three rows, first four columns, and first five depth slices
subarray = array_4d[:2, :3, :4, :5]

# Print the shape of the original 4D array and the selected subarray
print('Original 4D array shape:', array_4d.shape)
print('Selected subarray shape:', subarray.shape)
print('Selected subarray:\n', subarray)

Output:

Original 4D array shape: (3, 4, 5, 6)
Selected subarray shape: (2, 3, 4, 5)
Selected subarray:
 [[[[45 15 80 43 46]
   [39  9 61 70 69]
   [61 67 69 27 32]
   [24  5 85 61  8]]

  [[47 91 25 65 44]
   [95 74  0 54 38]
   [85 15 72 34  9]
   [ 6 17  7 95 19]]

  [[99 34 54  3  9]
   [63 49 59 35 35]
   [47 69 55 73 46]
   [19  8 66 56 59]]]


 [[[58 44 71 51  6]
   [52 32  2 20 94]
   [82 92 15 83  8]
   [57 38  0 38 89]]

  [[17 39 66 39 45]
   [71 40 11 57 41]
   [ 0 33 13 65 92]
   [83 98  0 93 28]]

  [[49 29 34 38 63]
   [ 1  1 34 83 13]
   [ 5 32 83 91 42]
   [33 47 14 62 57]]]]

Explanation:

  • Import Libraries:
    • Imported numpy as np for array creation and manipulation.
  • Create 4D NumPy Array:
    • Created a 4D NumPy array named array_4d with random integers ranging from 0 to 99 and a shape of (3, 4, 5, 6).
  • Multi-dimensional Indexing:
    • Used multi-dimensional indexing to select a subarray from array_4d. The subarray is defined by slicing the first two blocks, first three rows, first four columns, and first five depth slices.
  • Print Results:
    • Printed the shape of the original 4D array and the shape and content of the selected subarray to verify the indexing operation.

For more Practice: Solve these Related Problems:

  • Create a 4D array and extract a 3D subarray by specifying indices for the first two dimensions.
  • Write a function that selects a hyperplane from a 4D array using multi-dimensional slicing.
  • Implement an advanced indexing method to swap two dimensions in a 4D array and then extract a sub-block.
  • Extract elements from a 4D array by combining slicing with an index tuple to target specific regions.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Select elements from 3D NumPy array using Fancy indexing.
Next: Select elements from 2D NumPy array with random floats using Boolean indexing.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.