Select elements from 2D NumPy array with random floats using Boolean indexing
Boolean Indexing with Conditions:
Write a NumPy program that creates a 2D NumPy array of random floats and uses boolean indexing to select elements that satisfy multiple conditions (e.g., greater than 0.5 and less than 0.8).
Sample Solution:
Python Code:
import numpy as np
# Create a 2D NumPy array of random floats between 0 and 1
array_2d = np.random.rand(5, 5)
# Define the conditions
condition1 = array_2d > 0.5
condition2 = array_2d < 0.8
# Use boolean indexing to select elements that satisfy both conditions
selected_elements = array_2d[condition1 & condition2]
# Print the original array and the selected elements
print('Original 2D array:\n', array_2d)
print('Elements greater than 0.5 and less than 0.8:\n', selected_elements)
Output:
Original 2D array: [[0.52972276 0.70225957 0.27440778 0.18107896 0.11912977] [0.38789867 0.55283666 0.92619903 0.45360212 0.30341309] [0.96337533 0.11772659 0.57502825 0.6581205 0.40238651] [0.21598097 0.58864959 0.83392972 0.26703946 0.57283874] [0.67218407 0.19983269 0.23111841 0.24815625 0.22444408]] Elements greater than 0.5 and less than 0.8: [0.52972276 0.70225957 0.55283666 0.57502825 0.6581205 0.58864959 0.57283874 0.67218407]
Explanation:
- Import libraries:
- Imported numpy as np for array creation and manipulation.
- Create 2D NumPy Array:
- Create a 2D NumPy array named array_2d with random floats between 0 and 1 using np.random.rand.
- Define the conditions:
- Defined two conditions: condition1 to check if elements are greater than 0.5, and condition2 to check if elements are less than 0.8.
- Boolean Indexing:
- Applied boolean indexing to select elements that satisfy both conditions using the & operator to combine them.
- Print Results:
- Print the original 2D array and the elements that satisfy both conditions to verify the indexing operation.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics