w3resource

Select elements from 3D NumPy array using Fancy indexing

NumPy: Advanced Indexing Exercise-3 with Solution

Fancy Indexing:

Write a NumPy program that creates a 3D NumPy array and uses fancy indexing to select elements from specific rows and columns.

Sample Solution:

Python Code:

import numpy as np

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

# Define the row and column indices to select specific elements
row_indices = np.array([0, 1, 2])
col_indices = np.array([1, 2, 3])

# Use fancy indexing to select elements from specific rows and columns
selected_elements = array_3d[row_indices[:, np.newaxis], col_indices]

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

Output:

Original 3D array:
 [[[43 98 13 67 64]
  [ 9 88 72 87 34]
  [27 93  0 91 83]
  [40 48 50 71 81]]

 [[83  2 37 73 97]
  [ 8 60  2 72 68]
  [95 40 71 47 95]
  [55  3 18 17 46]]

 [[78 87 23 30 51]
  [67 57  8 18 72]
  [79 78 67 23 51]
  [44 82 68 33 89]]]
Row indices:
 [0 1 2]
Column indices:
 [1 2 3]
Selected elements:
 [[[ 9 88 72 87 34]
  [27 93  0 91 83]
  [40 48 50 71 81]]

 [[ 8 60  2 72 68]
  [95 40 71 47 95]
  [55  3 18 17 46]]

 [[67 57  8 18 72]
  [79 78 67 23 51]
  [44 82 68 33 89]]]

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 Row and Column Indices:
    • Defined row_indices and col_indices arrays to specify the rows and columns from which to select elements.
  • Fancy Indexing:
    • Used fancy indexing to select elements from array_3d based on row_indices and col_indices.
  • Print Results:
    • Print the original 3D array, the 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: Select elements from 1D NumPy array using integer Indexing.
Next: Select a Subarray from 4D NumPy array using Multi-dimensional indexing.

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