Table Of Contents
- Vectorization: Your Speed Multiplier
- Mathematical Operations at Light Speed
- Advanced Element-wise Patterns
- Speed Comparison: Loops vs Vectorization
- Custom Element-wise Functions
- Pro Tips for Maximum Performance
- Dive Deeper
Vectorization: Your Speed Multiplier
Forget slow Python loops. NumPy's element-wise operations happen at C speed, transforming your array computations from sluggish to supersonic.
Mathematical Operations at Light Speed
import numpy as np
# Basic arithmetic operations
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
# Element-wise operations
print(a + b) # [11 22 33 44]
print(a * b) # [10 40 90 160]
print(a ** 2) # [1 4 9 16]
print(b / a) # [10. 10. 10. 10.]
# Works with matrices too
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
result = matrix_a * matrix_b # Element-wise multiplication
print(result)
# [[ 5 12]
# [21 32]]
# Universal functions (ufuncs)
data = np.array([1, 4, 9, 16, 25])
print(np.sqrt(data)) # [1. 2. 3. 4. 5.]
print(np.exp(data)) # Exponential function
print(np.log(data)) # Natural logarithm
print(np.sin(data)) # Sine function
# Comparison operations
x = np.array([1, 5, 3, 8, 2])
print(x > 3) # [False True False True False]
print(x == 5) # [False True False False False]
# Logical operations
mask1 = x > 2
mask2 = x < 7
print(np.logical_and(mask1, mask2)) # [False True True False False]
print(mask1 & mask2) # Same as above
Advanced Element-wise Patterns
# Conditional operations
data = np.array([-2, -1, 0, 1, 2])
# Apply different operations based on condition
result = np.where(data >= 0, data**2, data*-1)
print(result) # [2 1 0 1 4]
# Clipping values
noisy_data = np.array([-10, 2, 15, -5, 8])
clipped = np.clip(noisy_data, 0, 10) # Clamp between 0 and 10
print(clipped) # [0 2 10 0 8]
# Broadcasting with scalars
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
result = matrix * 10 + 5 # Broadcast scalar operations
print(result)
# [[15 25 35]
# [45 55 65]]
Speed Comparison: Loops vs Vectorization
import time
# Python loop approach (slow)
def python_loop(arr):
result = []
for x in arr:
result.append(x**2 + 2*x + 1)
return result
# NumPy vectorized approach (fast)
def numpy_vectorized(arr):
return arr**2 + 2*arr + 1
# Test with large array
large_array = np.random.rand(1000000)
# The vectorized version is typically 10-100x faster!
Custom Element-wise Functions
# Create custom ufuncs
def custom_function(x):
return x**3 if x > 0 else 0
# Vectorize custom function
vectorized_func = np.vectorize(custom_function)
data = np.array([-2, -1, 0, 1, 2])
result = vectorized_func(data)
print(result) # [0 0 0 1 8]
Pro Tips for Maximum Performance
- Avoid Python loops with NumPy arrays
- Chain operations for better performance
- Use in-place operations when possible (
+=
,*=
) - Leverage broadcasting instead of reshaping
Dive Deeper
Master NumPy's universal functions, explore broadcasting mechanics, and learn about scientific computing optimization.
Share this article
Add Comment
No comments yet. Be the first to comment!