1. Introduction
Approach for Learning NumPy
- Focus on Capabilities over Memorisation: Avoid attempting to mug up or memorise specific syntaxes. Instead, understand what operations and structures are supported, and refer to the official documentation when writing code.
- Active Parallel Coding: Rather than passive watching, open tutorials and official documentation side-by-side with your environment. Write the code yourself to build confidence and muscle memory.
- Project-Driven Learning: The best way to internalise syntaxes is to work on end-to-end, hands-on projects where you write the same NumPy commands repeatedly.
Installing and Running NumPy
- Installation: In your terminal or a Jupyter notebook cell, install the package using
pip: - Importing: It is standard practice to import NumPy under the alias
npto keep code clean and standardised: - Interactive Environments: Using interactive environments like Jupyter notebooks allows you to execute blocks of code on-the-fly and check array shapes and dimensions immediately.
2. NumPy Fundamentals
Why NumPy Arrays? (Need and Internals)
At the core of the NumPy library is the NDArray (N-Dimensional Array) object. Standard Python lists have significant performance bottlenecks when handling large-scale data:- Homogeneity vs. Heterogeneity: Standard Python lists can contain heterogeneous data types, while NDArrays are homogeneous—all elements must share the exact same data type (e.g., all integers, all floats, or all strings).
- The Cost of Looping in Python: For large-scale math on millions of elements, Python lists require explicit, interpreted loops. This incurs heavy overhead because Python continually interprets the code and manipulates individual Python objects in memory.
- The C-Speed Under the Hood: NumPy operations are executed speedily at near-C speed. This is because NumPy relies on optimized, precompiled C code under the hood, saving the interpreter’s overhead and managing elements in contiguous memory blocks. It gives you the “best of both worlds”: the code simplicity of Python and the execution speed of C.
Vectorization
Vectorization is the absence of any explicit looping or indexing in your Python code.- Instead of looping over elements manually (
for x in array), you write standard mathematical notations (e.g.,C = A * B). - It produces concise, highly readable, and pythonic code with fewer lines and fewer bugs.
- Looping is implicitly offloaded to precompiled C code, making operations incredibly efficient.
Broadcasting
Broadcasting describes the implicit element-by-element behaviour of array operations.- By default, when an NDArray is involved, operations (arithmetic, logical, bitwise, or functional) happen element-wise.
- If you operate on two arrays of different shapes, NumPy evaluates if their dimensions are compatible.
- If they are compatible, NumPy expands the smaller array under the hood (without making actual copies in memory) until its shape matches the larger array, allowing the element-wise operation to proceed unambiguously. If they are incompatible, a
ValueErroris raised.
3. Creating Arrays
Creating Arrays
To instantiate a standard array from a Python list or iterable, usenp.array():
Zeros Array (np.zeros)
Creates an array filled entirely with zeros.
- Usage: Pass the desired shape as a single integer or a tuple.
- Note: Do not pass multiple dimensions as flat arguments (e.g.,
np.zeros(2, 3)), as NumPy will attempt to interpret the second argument as a data type. Always wrap multi-dimensional shapes in an outer tuple.
Ones Array (np.ones)
Creates an array filled entirely with ones, acting similarly to np.zeros.
Empty Array (np.empty)
Creates an uninitialised array of a specified shape.
- How it works: Instead of setting elements to zero or one,
np.emptysimply allocates the memory block and leaves whatever garbage values were already present in those memory addresses. - Why use it: It is faster than
np.zeros,np.ones, ornp.randombecause it avoids the overhead of value initialisation. It is highly useful when you plan to immediately overwrite every element in the array anyway.
Range Creation (np.arange)
Generates sequences of numbers over a range.
- Syntax:
np.arange([start], stop, [step]) - Default values:
startdefaults to0, andstepdefaults to1. - Inclusivity: The
stopvalue is not inclusive.
Linearly Spaced Arrays (np.linspace)
Generates a specified number of evenly spaced values over a specified interval.
- Key Difference from
arange: Instead of specifying a step size, you specify the exact number of elements you want. - Defaults: Returns elements as
float64by default. You can explicitly override this using thedtypeparameter.
Random Number Generation (np.random)
Modern NumPy uses a default generator object for producing random numbers.
- To use it, instantiate the generator first using
np.random.default_rng(). - Generate random integers within a range using the
.integers(low, high, size)method.
4. Array Properties
Knowing your array properties is essential for debugging structural errors and matching dimensional shapes.| Property | Method/Attribute | Description | Example |
|---|---|---|---|
| Dimensions | a.ndim | Returns the number of axes (dimensions) of the array. | Scalar (0D): 0Vector (1D): 1Matrix (2D): 2Tensor (>2D): 3+ |
| Shape | a.shape | Returns a tuple of non-negative integers specifying elements along each axis. | 2D matrix: (rows, columns)Scalar (0D): empty tuple () |
| Size | a.size | Total number of elements. Always equals the product of shape elements. | Shape (2, 4) size: 8 |
| Data Type | a.dtype | Identifies the homogeneous data type of the elements. | e.g., int64, float64 |
5. Indexing and Slicing
Accessing Elements
NumPy is zero-indexed. You access elements using square brackets.- Positive Indexing:
a[0]accesses the first element. - Negative Indexing:
a[-1]accesses the last element, anda[-2]accesses the second-to-last element.
Modifying Elements
You can mutate array elements in place by assigning a value directly to a targeted index.Basic Slicing
Extracts sections of an array using[start:stop:step] notation.
- Slices include the
startindex but exclude thestopindex.
Conditional (Boolean) Slicing
This is a powerful filtering technique where elements are selected based on logical conditions.- Generating a Boolean Mask: Running an operator like
a < 6returns an array ofTrue/Falseflags corresponding to whether each element meets the condition. - Filtering: Passing this mask back into the array returns a flat, new array containing only the elements where the mask is
True.
- Multiple Conditions: You can combine multiple logical conditions. You must wrap each condition in round brackets and use bitwise operators (
&for AND,|for OR).
- Retrieving Indices of Matches (
np.nonzero): If you want to find the indices where the condition is met instead of the values themselves, usenp.nonzero(condition). It returns a tuple of arrays (one for each dimension) containing coordinates of matching elements.
6. Array Manipulation
Reshaping Arrays (reshape)
Changes the shape structure of an array without modifying its underlying data.
- Sizing Constraint: The total size (number of elements) in the reshaped array must exactly match the original array size, otherwise NumPy throws a
ValueError.
- Row-Major vs. Column-Major Order (
order): You can control how elements are read/placed in memory during a reshape:order='C'(default, C-like order): Fills elements row-by-row.order='F'(Fortran-like order): Fills elements column-by-column.
Adding New Dimensions (np.newaxis, np.expand_dims)
Allows you to insert an extra dimension to convert vectors into explicit 2D row/column matrices without altering the underlying data.
Flattening Arrays (flatten, ravel)
Converts a multi-dimensional array into a flat 1D array.
ravel(Shallow/View): Returns a flattened view of the original array. Changes made to the ravelled array will directly mutate the original parent array. It is highly memory-efficient because no copy of the underlying data is made.flatten(Deep Copy): Returns a completely new 1D copy of the array. Modifying the flattened array will not affect the parent array.
Transposing Arrays (transpose, .T)
Transposes the matrix by swapping row indices with column indices.
- Access via
.Tor the.transpose()method. - Transposing twice returns the original array structure. It does not modify the original parent array in place.
Reversing/Flipping Arrays (flip, slicing)
Reverses the order of elements along axes.
np.flip(arr): Flips the elements across all axes.- Axis-Specific Flipping:
np.flip(arr, axis=0)reverses vertically along the rows.np.flip(arr, axis=1)reverses horizontally along the columns.
- Sub-array Flipping: You can flip targeted portions. For example,
np.flip(arr[1])reverses only the second row, whilenp.flip(arr[:, 1])reverses only the second column.
7. Combining and Splitting Arrays
Concatenation (concatenate)
Combines multiple arrays along a specified axis.
- By default,
axis=0is used, which vertically stacks them. - Constraint: All arrays must have matching dimensions except along the concatenation axis, or NumPy will raise an error.
Vertical Stacking (vstack)
Stacks arrays on top of each other (vertically along axis=0).
Horizontal Stacking (hstack)
Stacks arrays adjacent to each other side-by-side (horizontally along axis=1).
Horizontal Splitting (hsplit)
Splits an array horizontally along columns.
- Split into Equal Sections: Pass an integer specifying the number of equal sub-arrays.
- Split at Specific Coordinates: Pass a list of column indices where cuts should happen.
8. Sorting and Copying
Sorting Arrays (sort, argsort, partition)
np.sort: Returns a sorted copy of the array.np.argsort: Returns the indices that would sort the array, allowing you to perform indirect sorting.np.partition: Partitions an array around a specified indexk. All elements smaller than the element atkare shuffled to the left, and all larger elements are moved to the right. The elements on either side are not guaranteed to be sorted. This is highly useful for top-k selection algorithms.
Views vs. Copies
Understanding memory management in NumPy is critical to preventing unintended mutations.- Views (Shallow Copies): To save memory and execution overhead, basic operations like slicing and indexing return views rather than copies. If you modify a slice, the changes propagate to the original array.
- Deep Copies: If you need a completely isolated array, call the
.copy()method explicitly to allocate separate memory.
9. Mathematical Operations
Arithmetic Operations
All default arithmetic operations are executed element-by-element.- Addition (
+): Computes element-wise sum. - Subtraction (
-): Computes element-wise difference. - Multiplication (
*): Performs element-wise multiplication (this is not matrix multiplication). - Division (
/): Computes element-wise division.
ValueError is raised.
Aggregate Functions
Aggregations can collapse an entire array or be calculated along specific dimensions using theaxis parameter.
axis=0(Rows Axis): Computes operations vertically down columns.axis=1(Columns Axis): Computes operations horizontally across rows.
What’s next?
You know NUmpy! Let’s dive deeper into working next library Pandas.Pandas
Pandas library