w3resource

Select elements from 3D NumPy array using integer Indexing

NumPy: Advanced Indexing Exercise-11 with Solution

Integer Array Indexing on 3D Arrays:

Write a NumPy program that creates a 3D NumPy array and uses integer array indexing to select elements along specific axes.

Sample Solution:

Python Code:

import numpy as np

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

# Define the indices to select specific elements along each axis
depth_indices = np.array([0, 1, 2])
row_indices = np.array([1, 2, 3])
column_indices = np.array([2, 3, 4])

# Use integer array indexing to select elements along specific axes
selected_elements = array_3d[depth_indices[:, np.newaxis, np.newaxis], row_indices[:, np.newaxis], column_indices]

# Print the original array and the selected elements
print('Original 3D array:\n', array_3d)
print('Depth indices:\n', depth_indices)
print('Row indices:\n', row_indices)
print('Column indices:\n', column_indices)
print('Selected elements:\n', selected_elements)

Output:

 Original 3D array:
 [[[ 5 97 52 61 57]
  [79 87 75 83 21]
  [52  1 33 54 10]
  [76 58 44  0 72]]

 [[40  7 30 18 61]
  [24  1  9 98 25]
  [77 75  3 82  5]
  [90 63 59 79 52]]

 [[49 69 60 80 28]
  [45 60 63 31 69]
  [18 49 62 25 87]
  [85 94 35  9  8]]]
Depth indices:
 [0 1 2]
Row indices:
 [1 2 3]
Column indices:
 [2 3 4]
Selected elements:
 [[[75 83 21]
  [33 54 10]
  [44  0 72]]

 [[ 9 98 25]
  [ 3 82  5]
  [59 79 52]]

 [[63 31 69]
  [62 25 87]
  [35  9  8]]]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 3D NumPy Array:
    • Create a 3D NumPy array named array_3d with random integers ranging from 0 to 99 and a shape of (3, 4, 5).
  • Define Indices:
    • Defined depth_indices, row_indices, and column_indices arrays to specify the indices along the depth, row, and column axes, respectively.
  • Integer Array Indexing:
    • Used integer array indexing to select elements from 'array_3d' based on the specified depth, row, and column indices.
  • Print Results:
    • Print the original 3D array, the depth, row, and column indices, and the selected elements to verify the indexing operation.

Python-Numpy Code Editor:

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

Previous: Replace elements in 2D NumPy array using Boolean Indexing.
Next: Select Subset of elements using combined Indexing in NumPy.

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://w3resource.com/python-exercises/numpy/select-elements-from-3d-numpy-array-using-integer-indexing.php