Skip to content

Python Boolean Indexing

  • by

Boolean indexing is a powerful technique in Python, particularly in libraries like NumPy and pandas, that allows you to select elements from an array or DataFrame based on a boolean condition. This condition is usually expressed as a boolean array that has the same shape as the array or DataFrame you want to index.

Python Boolean Indexing example

Here’s an example of boolean indexing using both NumPy and pandas:

NumPy:

NumPy is a popular library for numerical computations in Python. Boolean indexing in NumPy allows you to select elements from an array based on a boolean condition.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
condition = arr > 2

result = arr[condition]
print(result)  # Outputs: [3, 4, 5]

pandas:

pandas is a widely-used library for data manipulation and analysis. Boolean indexing is commonly used to filter rows from a DataFrame based on a condition.

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 22, 28]}

df = pd.DataFrame(data)

condition = df['Age'] > 25
result = df[condition]

print(result)
# Outputs:
#    Name  Age
# 1   Bob   30
# 3  David   28

Combining Conditions:

You can also combine multiple conditions using logical operators like & (and) and | (or).

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
condition = (arr > 2) & (arr < 5)

result = arr[condition]
print(result)  # Outputs: [3, 4]

Last example

import pandas as pd

# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 22, 28]}

df = pd.DataFrame(data)

# Define a boolean condition
condition = df['Age'] > 25

# Apply boolean indexing
result = df[condition]

print("Original DataFrame:")
print(df)
print("\nCondition:")
print(condition)
print("\nFiltered Result:")
print(result)

Output:

Python Boolean Indexing

Boolean indexing allows you to filter, modify, or perform calculations on specific elements of an array or DataFrame based on your specified conditions. It’s an essential tool for data manipulation, analysis, and filtering in Python programming.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading