Boolean arrays help us mark True or False values for data. They are useful to filter or select data easily.
Creating boolean arrays in NumPy
import numpy as np # Create a boolean array from a condition array = np.array([1, 2, 3, 4, 5]) boolean_array = array > 3 # Create a boolean array directly bool_array = np.array([True, False, True])
You can create boolean arrays by comparing arrays with conditions like >, <, ==.
Boolean arrays have values True or False only.
import numpy as np # Empty array empty_array = np.array([]) boolean_empty = empty_array > 0 print(boolean_empty)
import numpy as np # Single element array single_element_array = np.array([10]) boolean_single = single_element_array == 10 print(boolean_single)
import numpy as np # Condition at the start and end array = np.array([5, 3, 7, 1, 5]) boolean_condition = (array == 5) print(boolean_condition)
This program creates a boolean array by checking which numbers are greater than 5. Then it uses this boolean array to select only those numbers from the original array.
import numpy as np # Create an array of numbers numbers = np.array([2, 4, 6, 8, 10]) print("Original array:", numbers) # Create a boolean array where numbers are greater than 5 greater_than_five = numbers > 5 print("Boolean array (numbers > 5):", greater_than_five) # Use boolean array to filter numbers filtered_numbers = numbers[greater_than_five] print("Filtered numbers (only > 5):", filtered_numbers)
Time complexity: Creating a boolean array is O(n), where n is the number of elements.
Space complexity: Boolean arrays use less memory than integer arrays but still proportional to n.
Common mistake: Forgetting that boolean arrays are masks and must be used to index the original array for filtering.
Use boolean arrays when you want to select or mark elements based on conditions. For simple checks, use direct comparisons.
Boolean arrays store True/False values for each element.
They are created by applying conditions to arrays.
Boolean arrays help filter or select data easily.