Skip to content

Python Boolean Array

  • by

A Python Boolean array typically refers to a NumPy array with a dtype of bool, where each element of the array can either be True or False. NumPy is a powerful library for numerical computations in Python, and it provides support for creating and manipulating arrays efficiently.

Python Boolean Array example

Here’s how you can create and work with a Boolean array using NumPy:

Import NumPy: Before using NumPy, make sure you have it installed. You can install it using the following command:

pip install numpy

Then, import it in your Python script or interactive session:

import numpy as np

Creating Boolean Arrays: You can create Boolean arrays in several ways. For instance:

# Creating a Boolean array with specific values
bool_array = np.array([True, False, True, True])

# Creating a Boolean array of a specific shape with all elements initialized to False
shape = (3, 4)  # Example shape
bool_array_zeros = np.zeros(shape, dtype=bool)

# Creating a Boolean array of a specific shape with all elements initialized to True
bool_array_ones = np.ones(shape, dtype=bool)

Array Operations: Boolean arrays can be used for various logical operations, indexing, and more.

# Element-wise logical operations
a = np.array([True, True, False, False])
b = np.array([True, False, True, False])
result_and = np.logical_and(a, b)  # Element-wise AND
result_or = np.logical_or(a, b)    # Element-wise OR
result_not = np.logical_not(a)     # Element-wise NOT

# Indexing with Boolean arrays
values = np.array([1, 2, 3, 4])
selected_values = values[a]  # Select values where a is True

# Counting True values in a Boolean array
count_true = np.count_nonzero(a)

Boolean Indexing: Boolean arrays can be used to index other arrays and select elements based on conditions.

data = np.array([10, 20, 30, 40, 50])
condition = np.array([True, False, True, False, True])

selected_data = data[condition]  # Select elements where condition is True

Here’s a simple example of creating and working with a Boolean array using NumPy:

import numpy as np

# Creating a Boolean array
data = np.array([10, 20, 30, 40, 50])
condition = data > 30

print("Original data:", data)
print("Boolean condition:", condition)

# Using Boolean indexing to select elements
selected_data = data[condition]

print("Selected data:", selected_data)

# Counting True values in the Boolean array
count_true = np.count_nonzero(condition)
print("Count of True values:", count_true)

Output:

Python Boolean Array

Boolean arrays are useful for various tasks, such as filtering data, masking arrays, and performing conditional computations. NumPy provides a wide range of functions and methods for working with Boolean arrays and performing efficient numerical computations.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *