The Ultimate NumPy Cheatsheet (Interactive)
This comprehensive cheat sheet provides interactive examples for learning NumPy, the fundamental Python library for numerical computing and array operations.
import numpy as np
The NumPy ndarray Object
The core of NumPy is the ndarray, an efficient, fixed-size, homogeneous array.
Key ndarray Attributes
type(data): Check the type of the array. Returns<class 'numpy.ndarray'>data: View the array content (raw data buffer).ndim: The number of dimensions (axes). Returns integer value.shape: A tuple indicating the size of the array in each dimension. Returns(rows, columns, ...).size: The total number of elements. Returns integer value.dtype: The data type of the elements. Returns dtype object.nbytes: The total bytes consumed by the array's elements. Returns integer value.T: The transposed array (swaps dimensions)
Data Types and Type Casting
Specifying dtype on Creation
np.array(..., dtype=int): Create an array with integer typenp.array(..., dtype=float): Create an array with float typenp.array(..., dtype=complex): Create an array with complex type
Casting Data Types
np.array(data, dtype=int): Cast usingnp.arrayconstructor.astype(): Convert an array to a different data type
Type Promotion in Operations
Type Promotion: How types are promoted during operations (e.g., int + float = float)
Data Type Affecting Function Behavior
np.sqrt()with real numbers: Square root of negative numbers returns NaNnp.sqrt()with complex numbers: Square root with complex dtype handles negative numbers
Real and Imaginary Parts
.real: Get the real part of a complex array.imag: Get the imaginary part of a complex array
Array Creation
From Existing Data & Sequences
np.array(1D list): Create a 1D array from a Python listnp.array(2D list): Create a 2D array from a list of listsnp.arange(): Create an array with regularly spaced values (step)np.arange(float): Create an array with float stepnp.linspace(): Create an array with a specific number of evenly spaced valuesnp.linspace(0, 10, 11): Example of linspacenp.logspace(): Create logarithmically spaced values
Initial Placeholders
np.zeros()/np.ones(): Create an array filled with zeros or onesnp.zeros(2x3): Example ofnp.zerosnp.ones(4): Example ofnp.onesnp.ones(dtype):np.oneswith specified dtypenp.full()/np.empty(): Create a constant or uninitialized arraynp.full()with value: Example ofnp.fullnp.empty(): Example ofnp.emptynp.eye()/np.identity(): Create an identity matrixnp.identity(4): Example ofnp.identitynp.eye(k=1): Example ofnp.eyewith offsetnp.diag(): Create a diagonal arraynp.random.*: Create arrays with random values
Meshgrid Arrays
np.meshgrid(): Create coordinate matrices from coordinate vectors
Indexing, Slicing, and Subsetting
1D Arrays Indexing & Slicing
np.arange(0, 11): Example array for 1D indexinga[0]: Access the first elementa[-1]: Access the last elementa[4]: Access the fifth elementa[1:-1]: Slice from index 1 to -1a[1:-1:2]: Slice with step 2a[:5]: Slice up to index 5a[-5:]: Slice from -5 to enda[::-2]: Reverse slice with step 2
2D Arrays Indexing & Slicing
np.fromfunction(): Create a 2D array using a functionA[:, 1]: Select a columnA[1, :]: Select a rowA[:3, :3]: Select a blockA[::2, ::2]: Select every second element
Fancy and Boolean Indexing
- Fancy Indexing (array): Using a NumPy array of indices
- Fancy Indexing (list): Using a Python list of indices
- Boolean Mask: Create a boolean mask
- Boolean Filtering: Filter data using a boolean mask
Views vs. Copies
Understanding Views and Copies: Slices create views, while boolean/fancy indexing creates copies.
.copy(): Force the creation of a copy
Array Manipulation
Reshaping
.reshape(): Change the shape of an array without changing its datanp.reshape(data, (1, 4)): Example ofnp.reshape.ravel()/.flatten(): Flatten an array to 1D (view vs. copy).flatten(): Example of.flatten()np.newaxis(column): Add a new axis to create a column vectornp.newaxis(row): Add a new axis to create a row vector
Combining and Splitting
np.concatenate(): Join a sequence of arrays along an existing axisnp.vstack()/np.hstack(): Stack arrays vertically or horizontallynp.vstack(): Example of vertical stackingnp.hstack(): Example of horizontal stacking
Vectorized Expressions and Operations
Element-wise Operations (UFuncs)
- Arithmetic: Standard operators (
+,-,*,/,**) work element-wise - Element-wise Addition: Example of
+ - Element-wise Multiplication: Example of
* - Element-wise Division: Example of
/ - Universal Functions: Functions like
np.sqrt(),np.sin(),np.log()
Aggregate Functions
.sum()/.mean()/.std(): Compute sum, mean, standard deviation, etc.np.mean(): Mean of random data.mean(): Mean using method.sum()(all): Sum of all elements.sum(axis=0): Sum along columns.sum(axis=1): Sum along rows.min()/.max()/.argmin()/.argmax(): Find min/max values and their indices
Matrix and Vector Operations
@or.dot(): Matrix multiplicationnp.dot(A, x): Matrix-vector multiplicationA.dot(x): Matrix-vector multiplication (method)np.dot(A, B): Matrix-matrix multiplicationnp.dot(x, x): Inner productnp.outer(x, x): Outer product
Implementation Notes
This content was originally designed with interactive JavaScript modals for each clickable term. In the Markdown version, you can implement interactivity by:
- Adding click handlers to code elements for showing explanations
- Creating collapsible sections for detailed examples
- Using JavaScript to generate dynamic examples
- Implementing tooltips for inline explanations
Interactive Features (Future Implementation)
- Click on any
codeelement to see detailed explanation - Expandable sections for code examples
- Live execution of NumPy operations
- Step-by-step tutorials for complex operations
This NumPy cheatsheet covers the essential concepts and operations you'll need for scientific computing and data science applications.
Updated: January 15, 2025
Author: Danial Pahlavan
Category: Data Science & Scientific Computing