NumPy Array Filter

Filtering in NumPy allows you to extract elements based on specific conditions. This is a powerful tool for data analysis, such as finding temperatures above a threshold or identifying rainfall below a certain value.

Key Topics

Filtering 1D Arrays

Use conditional expressions to create a boolean mask and apply it to the array to extract filtered elements.

Example

# Filtering a 1D array
import numpy as np

temperatures_madurai = np.array([29, 34, 31, 28, 35, 30])
# Filter for temperatures above 30 degrees
hot_days = temperatures_madurai[temperatures_madurai > 30]

print("Hot temperatures in Madurai:", hot_days)

Output

Hot temperatures in Madurai: [34 31 35]

Explanation: The condition temperatures_madurai > 30 creates a boolean mask, which is then applied to the array to filter values greater than 30.

Filtering 2D Arrays

For 2D arrays, you can apply conditions to extract elements or entire rows/columns that meet the criteria.

Example

# Filtering a 2D array
rainfall_data = np.array([[120, 150, 80], [90, 110, 70]])

# Filter for rainfall above 100 mm
high_rainfall = rainfall_data[rainfall_data > 100]

print("High rainfall values:", high_rainfall)

Output

High rainfall values: [120 150 110]

Explanation: The condition rainfall_data > 100 creates a boolean mask to extract all rainfall values greater than 100 mm from the 2D array.

Key Takeaways

  • 1D Filtering: Apply conditions directly to extract elements that meet the criteria.
  • 2D Filtering: Use conditions to extract elements, rows, or columns from 2D arrays.
  • Flexible Conditions: Combine multiple conditions using logical operators (e.g., &, |).
  • Example Use: Filter datasets like temperatures in Madurai or rainfall in specific regions for targeted analysis.