Mathematical Operations
Overview
Perform mathematical operations, aggregations, and utilize helper generator functions inside NumPy.
Learning Objectives
- Perform arithmetic operations and aggregations on arrays.
- Generate numeric sequences and helper templates using zeros, ones, arange, and linspace.
- Implement conditional array modification checks using np.where.
Concept Explanation
NumPy uses vectorization to run computations across entire arrays in optimized C loops instead of slow Python loops. It provides helpers like zeros() and ones() to instantiate empty arrays, arange() and linspace() to generate numeric sequences, and np.where() to write conditional filter checks.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
import numpy as np
# Generate template arrays
zeros_arr = np.zeros(5)
ones_matrix = np.ones((2, 2))
range_arr = np.arange(5)
print(zeros_arr, range_arr)
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Perform aggregations across rows and columns
transactions = np.array([
[100.0, 200.0],
[150.0, 250.0]
])
print('Total sum:', transactions.sum())
print('Mean per column (axis=0):', transactions.mean(axis=0))
print('Mean per row (axis=1):', transactions.mean(axis=1))
Example 3 — Practical Data Engineering Example
This example shows clean, production-grade code structure following senior development standards.
# Clean sentinel error numbers in logs and scale data using vectorized z-scores
sensor_readings = np.array([12.5, -99.9, 14.0, -99.9, 13.5])
# Replace -99.9 error markers with a clean default value of 12.0
cleaned_readings = np.where(sensor_readings == -99.9, 12.0, sensor_readings)
# Standard z-score scale
z_scores = (cleaned_readings - cleaned_readings.mean()) / cleaned_readings.std()
print('Z-Scores:', z_scores)
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Input values array → Apply condition mask (np.where) → Substitute matches → Return clean array
Common Mistakes
Review these common pitfalls when working with this topic:
- Using python's loops to do math on arrays.
- Forgetting to pass dimensions as a tuple when using zeros or ones (e.g. zeros(2, 3); use zeros((2, 3))).
- Confusing arange (step size) with linspace (number of elements).
- Not matching shape requirements inside broadcast conditions.
Best Practices
Enforce these Pythonic best practices in your codebase:
for i in range(len(arr)):
arr[i] = arr[i] * 5 # Slow manual iteration
arr = arr * 5 # Fast vectorized execution
Performance Notes
Keep these optimization guidelines in mind for performance-sensitive hotpaths:
- Vectorized operations run in compiled C code, executing up to 100x faster than standard Python loops.
Quick Revision
Use these key summaries for last-minute revision:
- Vectorization executes operations in native C loops.
- zeros() and ones() initialize template arrays.
- arange() generates numeric intervals.
- linspace() generates evenly spaced numbers.
- np.where(cond, x, y) filters and substitutes values.