0
0
NumPydata~5 mins

Boolean type in NumPy

Choose your learning style9 modes available
Introduction

Boolean type helps us store True or False values. It is useful to check conditions and filter data easily.

When you want to mark data as True or False, like if a student passed or failed.
When filtering data, for example, selecting only numbers greater than 10.
When you want to create masks to pick certain rows or columns in a dataset.
Syntax
NumPy
numpy.bool_

This is the Boolean type in numpy, which stores True or False values.

It is different from Python's built-in bool but works similarly in numpy arrays.

Examples
This creates a numpy array of boolean values.
NumPy
import numpy as np

# Create a boolean numpy array
bool_arr = np.array([True, False, True], dtype=np.bool_)
print(bool_arr)
This shows how boolean arrays can filter values greater than 10.
NumPy
import numpy as np

# Use boolean type to filter data
data = np.array([5, 10, 15, 20])
mask = data > 10
print(mask)
print(data[mask])
Sample Program

This program creates a boolean array and uses it to select elements from another array.

NumPy
import numpy as np

# Create a numpy array with boolean type
bool_array = np.array([True, False, True, False], dtype=np.bool_)

# Print the array
print('Boolean array:', bool_array)

# Use boolean array to filter another array
numbers = np.array([1, 2, 3, 4])
filtered_numbers = numbers[bool_array]
print('Filtered numbers:', filtered_numbers)
OutputSuccess
Important Notes

Boolean arrays are very useful for selecting or masking data in numpy.

Use dtype=np.bool_ to explicitly create boolean numpy arrays.

Summary

Boolean type stores True or False values in numpy.

It helps filter and select data easily.

Use boolean arrays as masks to pick data from other arrays.