0
0
NumPydata~5 mins

Creating boolean arrays in NumPy

Choose your learning style9 modes available
Introduction

Boolean arrays help us mark True or False values for data. They are useful to filter or select data easily.

To mark which data points meet a condition, like scores above 50.
To filter rows in a table where a condition is True.
To create masks for images or data to highlight certain parts.
To quickly check if elements in an array satisfy a rule.
To combine multiple conditions for data selection.
Syntax
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.

Examples
Boolean array from an empty array results in an empty boolean array.
NumPy
import numpy as np

# Empty array
empty_array = np.array([])
boolean_empty = empty_array > 0
print(boolean_empty)
Boolean array with one element shows True if condition matches.
NumPy
import numpy as np

# Single element array
single_element_array = np.array([10])
boolean_single = single_element_array == 10
print(boolean_single)
Boolean array marks True where elements equal 5, including first and last positions.
NumPy
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)
Sample Program

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.

NumPy
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)
OutputSuccess
Important Notes

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.

Summary

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.