NumPy Cheat Sheet
NumPy Cheat Sheet

NumPy Cheat Sheet

Tags
Machine Learning
Computer Science
Research
Published
December 18, 2024
Author
Junkai Ji

1. Array Creation and Initialization

  • np.array()
    • Creates a NumPy array from lists or tuples.
  • np.zeros(shape) / np.ones(shape)
    • Creates arrays filled with zeros or ones, often used for initializing weights or placeholders.
  • np.empty(shape)
    • Creates an array without initializing values (useful for pre-allocated storage).
  • np.full(shape, value)
    • Creates an array filled with a specified constant value.
  • np.arange(start, stop, step)
    • Generates an array of evenly spaced values within a given interval.
  • np.linspace(start, stop, num)
    • Creates an array of num evenly spaced values between start and stop.
  • np.eye(n) / np.identity(n)
    • Creates an identity matrix, commonly used in linear algebra.

2. Reshaping and Manipulating Arrays

  • array.reshape(shape)
    • Reshapes an array without changing its data.
  • array.flatten()
    • Flattens a multi-dimensional array to a one-dimensional array.
  • np.transpose(array) or array.T
    • Transposes an array, swapping rows and columns.
  • np.concatenate((a, b), axis=0/1)
    • Concatenates two arrays along a specified axis.
  • np.vstack() / np.hstack()
    • Stacks arrays vertically or horizontally.
  • np.split(array, sections)
    • Splits an array into multiple subarrays, useful for dividing data into batches.

3. Indexing and Slicing

  • Basic Indexing
    • Access specific elements using array[i] or array[i, j].
  • Slicing
    • Use array[start:stop:step] to extract subarrays.
  • Boolean Indexing
    • Select elements based on a condition:
      array[array > 0]
  • Fancy Indexing
    • Select specific elements using an array of indices:
      array[[1, 2, 4]]

4. Mathematical and Statistical Operations

  • Element-wise Operations
    • Use standard operators (+, -, *, /) for element-wise calculations.
  • Aggregations
    • np.sum(array, axis=None): Computes the sum across specified axes.
    • np.mean(array, axis=None): Calculates the mean across specified axes.
    • np.std(array, axis=None) / np.var(array, axis=None): Standard deviation and variance.
  • Min/Max Operations
    • np.min() / np.max(): Finds minimum and maximum values.
    • np.argmin() / np.argmax(): Finds indices of min/max values.
  • Element-wise Functions
    • np.exp(array): Exponential function.
    • np.log(array): Natural logarithm.
    • np.sqrt(array): Square root.
  • Matrix Operations
    • np.dot(a, b): Dot product of two arrays.
    • np.matmul(a, b) or a @ b: Matrix multiplication.

5. Random Number Generation

  • np.random.rand(d0, d1, ...)
    • Generates random values between 0 and 1 with the given shape.
  • np.random.randint(low, high, size)
    • Generates random integers between low and high.
  • np.random.randn(d0, d1, ...)
    • Generates random numbers from a standard normal distribution.
  • np.random.seed(seed)
    • Sets the random seed for reproducibility.

6. Linear Algebra and Matrix Operations

  • np.linalg.inv(array)
    • Computes the inverse of a matrix.
  • np.linalg.det(array)
    • Computes the determinant of a matrix.
  • np.linalg.eig(array)
    • Computes the eigenvalues and eigenvectors of a matrix.
  • np.linalg.svd(array)
    • Performs singular value decomposition (useful for dimensionality reduction).
  • np.linalg.norm(array)
    • Computes the norm (magnitude) of an array, useful for vector normalization.

7. Broadcasting

  • What is Broadcasting?
    • Enables NumPy to perform operations on arrays of different shapes by “stretching” them to compatible shapes.
  • Example
    • Adding a 1D array to a 2D array row-wise:
      array_2d + array_1d

8. Sorting and Searching

  • Sorting
    • np.sort(array): Sorts an array in ascending order.
    • np.argsort(array): Returns the indices that would sort the array.
  • Conditional Selection
    • np.where(condition, x, y): Chooses elements from x or y based on a condition.
  • Unique Elements
    • np.unique(array): Finds unique elements in an array.

9. Statistical Sampling

  • np.random.choice(array, size, replace)
    • Samples elements from an array with or without replacement.