Boolean indexing is a method used in programming, particularly in libraries like NumPy and Pandas, to select elements from an array or a DataFrame based on a boolean condition. It involves creating a boolean array (or mask) where each element corresponds to a condition applied to the original array. The elements that evaluate to True in the boolean array are selected, while those that evaluate to False are excluded.
Example in NumPy:
import numpy as np
# Creating a NumPy array
x = np.array([1, -1, -2, 3])
# Using boolean indexing to select elements less than 0
negative_elements = x[x < 0]
print(negative_elements) # Output: [-1 -2]
Example in Pandas:
import pandas as pd
# Creating a pandas Series
s = pd.Series([1, 2, 3, -1, -2])
# Creating a boolean mask
mask = s < 0
# Indexing the Series with the boolean mask
negative_values = s[mask]
print(negative_values) # Output: Series with -1 and -2
In both examples, boolean indexing allows you to filter and retrieve specific elements based on conditions efficiently.
