0
0
NumPydata~5 mins

Combining conditions in NumPy

Choose your learning style9 modes available
Introduction

We combine conditions to select or filter data that meets multiple rules at the same time. This helps us find exactly what we want in big data sets.

Finding people who are both older than 30 and live in a certain city.
Selecting products that cost less than $20 but have high ratings.
Filtering sensor data where temperature is above 50 and humidity is below 30.
Choosing students who passed math and science exams.
Extracting rows from a table where multiple conditions are true.
Syntax
NumPy
combined_condition = (condition1) & (condition2)
combined_condition = (condition1) | (condition2)
combined_condition = ~(condition1)

Use & for AND, | for OR, and ~ for NOT.

Always put each condition inside parentheses to avoid errors.

Examples
Select numbers greater than 20 AND less than 50.
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
condition = (arr > 20) & (arr < 50)
print(arr[condition])
Select numbers less than 20 OR greater than 40.
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
condition = (arr < 20) | (arr > 40)
print(arr[condition])
Select numbers NOT equal to 30.
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
condition = ~(arr == 30)
print(arr[condition])
Sample Program

This program finds ages between 30 and 45 by combining two conditions with AND.

NumPy
import numpy as np

# Create an array of ages
ages = np.array([18, 25, 30, 35, 40, 45, 50])

# Condition 1: Age greater than or equal to 30
cond1 = ages >= 30

# Condition 2: Age less than or equal to 45
cond2 = ages <= 45

# Combine conditions with AND to find ages between 30 and 45 inclusive
combined = cond1 & cond2

# Print the filtered ages
print(ages[combined])
OutputSuccess
Important Notes

Use parentheses around each condition to avoid mistakes.

Use & for AND, | for OR, and ~ for NOT when combining numpy conditions.

Combined conditions return a boolean array you can use to filter data.

Summary

Combine conditions with & (AND), | (OR), and ~ (NOT).

Always put each condition inside parentheses.

Use combined conditions to filter numpy arrays easily.