w3resource

Boolean Indexing on 3D NumPy arrays with conditions

NumPy: Advanced Indexing Exercise-7 with Solution

Boolean Indexing on Multi-dimensional Arrays:

Write a NumPy program that creates a 3D NumPy array and use boolean indexing to select elements along one axis based on conditions applied to another axis.

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 condition to apply on the second axis (axis 1)
condition = array_3d[:, :, 0] > 50

# Use boolean indexing to select elements along the third axis (axis 2)
selected_elements = array_3d[condition]

# Print the original 3D array and the selected elements
print('Original 3D array:\n', array_3d)
print('Condition array (elements along second axis where first element > 50):\n', condition)
print('Selected elements along third axis based on condition:\n', selected_elements)

Output:

Original 3D array:
 [[[53  8 69 33 11]
  [54 91  9 13 78]
  [92 26  6 24 84]
  [19 21 20 74 24]]

 [[65 46 48 57 31]
  [12 62 64 73 68]
  [55 61 61 62 31]
  [16 34 35 64 25]]

 [[24 85 19 60 27]
  [25 26 59 78 81]
  [89 77 22 29 60]
  [ 9 32 45 62 25]]]
Condition array (elements along second axis where first element > 50):
 [[ True  True  True False]
 [ True False  True False]
 [False False  True False]]
Selected elements along third axis based on condition:
 [[53  8 69 33 11]
 [54 91  9 13 78]
 [92 26  6 24 84]
 [65 46 48 57 31]
 [55 61 61 62 31]
 [89 77 22 29 60]]

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 Condition:
    • Define a condition to apply on the second axis (axis 1) by checking if the first element along the third axis (axis 2) is greater than 50.
  • Boolean Indexing:
    • Applied boolean indexing to select elements along the third axis (axis 2) based on the condition applied to the second axis (axis 1).
  • Print Results:
    • Print the original 3D array, the condition array, 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 2D NumPy array using integer Indexing.
Next: Index and select elements in 2D NumPy Array using Tuple of arrays

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/boolean-indexing-on-3d-numpy-arrays-with-conditions.php