w3resource

Extract smaller Subarrays using integer Indexing in NumPy

NumPy: Advanced Indexing Exercise-17 with Solution

Extracting Subarrays with Integer Indexing:

Write a NumPy program that creates a 4D NumPy array and uses integer indexing to extract smaller subarrays.

Sample Solution:

Python Code:

import numpy as np

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

# Define indices to extract subarrays
depth_indices = np.array([0, 2])
row_indices = np.array([1, 3])
col_indices = np.array([0, 2])
slice_indices = np.array([1, 3])

# Use integer indexing to extract smaller subarrays
subarray = array_4d[depth_indices[:, np.newaxis, np.newaxis, np.newaxis],
                    row_indices[:, np.newaxis, np.newaxis],
                    col_indices[:, np.newaxis],
                    slice_indices]

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

Output:

Original 4D array shape: (4, 4, 4, 4)
Extracted subarray shape: (2, 2, 2, 2)
Extracted subarray:
 [[[[38 79]
   [15 79]]

  [[22  6]
   [28 90]]]


 [[[61 18]
   [43 69]]

  [[20 59]
   [65 89]]]]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 4D NumPy Array:
    • Create a 4D NumPy array named array_4d with random integers ranging from 0 to 99 and a shape of (4, 4, 4, 4).
  • Define Indices:
    • Defined depth_indices, row_indices, col_indices, and slice_indices to specify the indices for extracting subarrays along each axis.
  • Integer Indexing:
    • Used integer indexing to extract subarrays from 'array_4d' based on the specified indices for each axis.
  • Print Results:
    • Print the shape of the original 4D array, the shape of the extracted subarray, and the extracted subarray itself to verify the operation.

Python-Numpy Code Editor:

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

Previous: Find and Index elements in 2D NumPy array using np.nonzero.
Next: Combine slicing and Indexing in NumPy to select elements.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/extract-smaller-subarrays-using-integer-indexing-in-numpy.php