Advanced Array Techniques
Fancy Indexing
import numpy as np
## Create sample array
arr = np.array([10, 20, 30, 40, 50])
## Boolean indexing
mask = arr > 25
filtered_arr = arr[mask]
## Integer array indexing
indices = np.array([0, 2, 4])
selected_elements = arr[indices]
Structured Arrays
## Creating structured arrays
employee_dtype = np.dtype([
('name', 'U10'),
('age', 'i4'),
('salary', 'f8')
])
employees = np.array([
('Alice', 30, 5000.0),
('Bob', 35, 6000.0)
], dtype=employee_dtype)
Advanced Reshaping Techniques
graph TD
A[Array Reshaping] --> B[Flatten]
A --> C[Ravel]
A --> D[Transpose]
A --> E[Resize]
Technique |
Description |
Example |
flatten() |
Creates copy of flattened array |
arr.flatten() |
ravel() |
Creates view of flattened array |
arr.ravel() |
reshape() |
Changes array dimensions |
arr.reshape(2,3) |
Vectorized Operations
## Vectorized conditional assignment
arr = np.array([1, 2, 3, 4, 5])
np.where(arr > 3, arr * 2, arr)
## Universal functions (ufuncs)
def custom_operation(x):
return x ** 2 + 2 * x
vectorized_func = np.vectorize(custom_operation)
result = vectorized_func(arr)
Memory-Efficient Techniques
## Memory views and references
a = np.arange(10)
b = a[2:7] ## Creates a view, not a copy
## Memory-efficient data types
small_int_array = np.array([1, 2, 3], dtype=np.int8)
Advanced Numerical Computations
## Linear algebra operations
matrix = np.random.rand(3, 3)
## Matrix decompositions
U, S, V = np.linalg.svd(matrix)
## Solving linear equations
A = np.array([[1, 2], [3, 4]])
B = np.array([5, 11])
solution = np.linalg.solve(A, B)
## Numba acceleration
from numba import jit
@jit(nopython=True)
def fast_computation(arr):
return arr ** 2 + 2 * arr
Random Number Generation
## Advanced random generation
random_normal = np.random.normal(0, 1, (3, 3))
random_uniform = np.random.uniform(0, 1, (2, 2))
LabEx Pro Tip
Advanced array techniques require practice. LabEx recommends experimenting with different methods to understand their nuanced behaviors and performance characteristics.
Best Practices
- Use vectorization for performance
- Understand memory management
- Leverage specialized NumPy functions
- Profile and optimize numerical computations