Select elements using Boolean Indexing with logical operators
NumPy: Advanced Indexing Exercise-13 with Solution
Boolean Indexing with Logical Operators:
Write a NumPy program that creates a 1D NumPy array and uses boolean indexing with logical operators (e.g., & for AND, | for OR) to select elements based on multiple conditions.
Sample Solution:
Python Code:
import numpy as np
# Create a 1D NumPy array with random integers
array_1d = np.random.randint(0, 100, size=20)
# Define multiple conditions using logical operators
condition = (array_1d > 30) & (array_1d < 70) | (array_1d % 10 == 0)
# Use boolean indexing to select elements that meet the conditions
selected_elements = array_1d[condition]
# Print the original array and the selected elements
print('Original 1D array:\n', array_1d)
print('Condition (elements > 30 AND < 70 OR divisible by 10):\n', condition)
print('Selected elements:\n', selected_elements)
Output:
Original 1D array: [62 59 48 29 54 10 10 59 11 94 64 3 99 37 52 75 16 60 97 77] Condition (elements > 30 AND < 70 OR divisible by 10): [ True True True False True True True True False False True False False True True False False True False False] Selected elements: [62 59 48 54 10 10 59 64 37 52 60]
Explanation:
- Import Libraries:
- Imported numpy as np for array creation and manipulation.
- Create 1D NumPy Array:
- Create a 1D NumPy array named array_1d with random integers ranging from 0 to 99 and a length of 20.
- Define Multiple Conditions:
- Define multiple conditions using logical operators:
- Elements greater than 30 (array_1d > 30)
- Elements less than 70 (array_1d < 70)
- Elements divisible by 10 (array_1d % 10 == 0)
- Combine these conditions using & (AND) and | (OR) logical operators.
- Boolean Indexing:
- Applied boolean indexing to select elements in array_1d that meet the defined conditions.
- Print Results:
- Print the original 1D array, the boolean 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 Subset of elements using combined Indexing in NumPy.
Next: Select Rectangular Subarray using advanced slicing in NumPy.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-using-boolean-indexing-with-logical-operators.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics