NumPy Fundamentals Cheat Sheet
NumPy arrays enable efficient numerical operations in Python, offering distinct advantages over standard lists for mathematical computations due to their fixed data types and vectorized operations.
Core Principles
- NumPy arrays require all elements to be of the same data type, unlike Python lists which can hold mixed types. This homogeneity allows for optimized memory usage and faster computations.
- Vectorized operations, implemented via Universal Functions (ufuncs), allow NumPy to perform element-wise operations quickly by leveraging optimized, compiled routines.
- NumPy arrays support multi-dimensional structures, enabling the representation of matrices and tensors, with operations like concatenation, splitting, and aggregation applied along specified axes.
- NumPy provides functions for creating arrays with specific initial values (zeros, ones, full) or sequences (arange, linspace), offering more control than manual list creation.
- Array arithmetic in NumPy, including addition, subtraction, multiplication, division, exponentiation, and modulus, is performed element-wise and is highly efficient.
- NumPy offers powerful aggregation functions (sum, mean, min, max, median) that can operate on the entire array or along specific axes (rows or columns).
Action Steps
- Import the NumPy library using the convention `import numpy as np` to access its functionalities.
- Create 1D NumPy arrays using `np.array()` with a list of numbers, e.g., `np.array([1, 2, 3])`.
- Create 2D NumPy arrays by passing a list of lists to `np.array()`, e.g., `np.array([[1, 2], [3, 4]])`.
- Perform element-wise arithmetic operations by directly using operators like `+`, `-`, `*`, `/` on NumPy arrays.
- Use `np.concatenate()` to join arrays along an existing axis, or `np.vstack()` for vertical stacking and `np.hstack()` for horizontal stacking when dimensions differ.
- Split arrays using `np.split()`, `np.vsplit()` (vertical), or `np.hsplit()` (horizontal) by specifying the split points.
- Apply universal functions (ufuncs) like `np.sin()`, `np.cos()`, `np.exp()`, `np.log()` for mathematical transformations on array elements.
- Utilize aggregation functions like `np.sum()`, `np.mean()`, `np.min()`, `np.max()`, `np.median()` to compute statistics over arrays, specifying `axis` for targeted calculations.
- Sort arrays using `np.sort()` for a new sorted array or `array.sort()` to sort in-place.
Key Terms
- NumPy Array: A fundamental data structure in NumPy that holds elements of the same type in a grid-like manner, optimized for numerical operations.
- Ufunc (Universal Function): NumPy functions that perform element-wise operations on arrays efficiently, such as `np.sin()`, `np.exp()`, `np.add()`.
- Vectorized Operation: Operations that apply to entire arrays at once, implemented via ufuncs, eliminating the need for explicit Python loops and significantly speeding up computations.
- Upcasting: The process where NumPy automatically converts elements to a more general data type (e.g., int to float) when mixing types in an array to maintain homogeneity.
- Axis: A dimension in a NumPy array; `axis=0` typically refers to rows (vertical operations) and `axis=1` refers to columns (horizontal operations) in a 2D array.
Pro Tips
- When creating arrays with mixed data types (e.g., integers and floats), NumPy will 'upcast' to the most general type (float) to maintain consistency.
- Accessing elements in multi-dimensional arrays uses comma-separated indices, e.g., `N[row, column]`, which is more efficient than nested list indexing like `N[row][column]`.
- Negative indices in NumPy arrays, like in Python lists, count from the end of the array, with `-1` referring to the last element.
- NumPy's `arange()` function is similar to Python's `range()` but returns an array and can handle floating-point steps.
- For operations that might encounter NaN (Not a Number) values, use the `nan`-safe versions of functions like `np.nansum()` or `np.nanmean()` to ignore NaNs.
Pitfalls to Avoid
- Attempting to add lists of different lengths using the `+` operator will result in concatenation, not element-wise addition, unlike NumPy arrays.
- Inserting a floating-point value into an integer NumPy array will result in silent truncation of the decimal part, as arrays have a fixed type.
- Using `np.concatenate()` with arrays of incompatible shapes along the specified axis will raise an error; use `np.vstack()` or `np.hstack()` for arrays with differing dimensions.
Myth vs Reality
- Python lists can perform element-wise addition like mathematical vectors.: Python lists concatenate when the `+` operator is used; element-wise addition requires explicit looping or NumPy arrays.
- NumPy arrays can hold elements of different data types.: NumPy arrays enforce a single data type for all elements, upcasting if necessary, to ensure efficient computation.
Real World Examples
- Performing element-wise addition of two lists representing vectors.: Using `np.array([list1]) + np.array([list2])` for efficient vector addition instead of manual looping.
- Calculating the sine of each element in an array in degrees.: Using `np.sin(np.radians(array))` to apply the sine function element-wise after converting degrees to radians.
- Creating a 5x2 matrix filled with zeros.: Using `np.zeros((5, 2), dtype=int)` to initialize a matrix of the desired shape and type.
Statistics
- Number of dimensions in example matrix N: 2
- Shape of example matrix N: 3x4
Quiz
- What is the primary difference between Python lists and NumPy arrays regarding element types?: Lists can hold mixed types; arrays must have a single type.
- Which NumPy function is used to join arrays along an existing axis?: np.concatenate()
- How do you perform element-wise multiplication of two NumPy arrays, `a` and `b`?: a * b
Related cheat sheets
More like this