Skip to content
Tutorials Center
My learning

Topics

NumPy Tutorial

Learn NumPy 2 from your first array to broadcasting, indexing, linear algebra, random numbers, performance and real projects. 49 lessons with live examples, quizzes and projects.

Start learning →

of lessons completed

Getting Started

  1. 1 What Is NumPy? Meet NumPy, the array library behind Python data science. See why ndarrays beat lists for numbers, run your first import, and learn where NumPy fits.
  2. 2 Installing NumPy and Using Jupyter Install NumPy 2 in a virtual environment with pip or uv, check the version, start JupyterLab, and learn notebook habits that keep numerical work reproducible.
  3. 3 Your First Arrays Build NumPy arrays from lists and nested lists, then read their ndim, shape, size, dtype, itemsize and nbytes. Learn how 1D, 2D and 3D arrays print.
  4. 4 Creating Arrays Create NumPy arrays without typing every value: zeros, ones, full, arange, linspace, logspace, eye, diag, meshgrid, fromfunction, tile and repeat.

Data Types

  1. 5 Data Types (dtype) Learn NumPy data types: int8 to int64, unsigned ints, float16 to float64, bool, complex and strings. Choose a dtype and avoid silent integer overflow.
  2. 6 Converting and Casting Types Convert NumPy dtypes with astype, learn how view differs, how casting rounds, how NumPy 2 promotion (NEP 50) works, and read finfo and iinfo limits.

Indexing and Selection

  1. 7 Indexing and Slicing Select elements and sub-arrays in NumPy with positive and negative indexes, slices with steps, a[i, j] on 2D arrays, ellipsis and newaxis. Slices are views.
  2. 8 Boolean Masks and Filtering Filter NumPy arrays with boolean masks, combine conditions with &, | and ~, use np.where, nonzero, any, all, select and clip to pick and replace values.
  3. 9 Fancy Indexing Select, reorder and overwrite NumPy array elements with lists of integer positions, pair up row and column indexes, and learn np.take, np.put and np.ix_.
  4. 10 Views vs Copies Learn when NumPy slicing, reshape, ravel and fancy indexing return a view or a copy, how to check with base and np.shares_memory, and how to avoid surprise bugs.

Array Math

  1. 11 Vectorized Operations and ufuncs Replace Python loops with NumPy vectorized arithmetic and universal functions: np.add, sqrt, exp, log, rounding, the out= argument and in-place operators.
  2. 12 Broadcasting Understand NumPy broadcasting step by step: the shape rules, scalar, row and column cases, np.newaxis, multiplication tables and how to fix shape mismatch errors.
  3. 13 Aggregations and Axes Summarize NumPy arrays with sum, mean, min, max, std, cumsum, argmax, median and percentile, understand the axis and keepdims arguments, and handle NaN safely.
  4. 14 Comparing Arrays and Floating Point Compare NumPy arrays safely. Learn array_equal, allclose and isclose with tolerances, how NaN and inf behave, logical operators and np.errstate.
  5. 15 Bitwise Operations and Integer Functions Use NumPy bitwise_and, bitwise_or, bitwise_xor, invert and shifts on integer arrays, build flag masks, and meet gcd, lcm, packbits and unpackbits with runnable examples.

Shapes and Combining

  1. 16 Reshaping Arrays Change the shape of NumPy arrays without copying data. Learn reshape with -1, ravel vs flatten, transpose, moveaxis, squeeze, expand_dims and C vs F order.
  2. 17 Joining and Splitting Combine and cut NumPy arrays. Learn concatenate vs stack, vstack, hstack, column_stack, split, array_split, append, insert and delete, with runnable examples.
  3. 18 Sorting and Searching Sort and search NumPy arrays quickly. Learn sort vs np.sort, argsort, axis sorting, lexsort, partition, searchsorted, argwhere and stable sorts.
  4. 19 Unique Values, Sets and Counting Find distinct values, do set operations and count occurrences with NumPy. Covers unique, isin, union1d, intersect1d, setdiff1d, bincount, histogram and digitize.
  5. 20 Small Array Utilities You Will Meet Sooner or Later Learn the handy NumPy helpers resize, trim_zeros, flip, fliplr, flipud, nditer, ndenumerate, extract, fromiter and fromfunction, with a 2-D Gaussian grid example.

Linear Algebra

  1. 21 Vectors, Dot Products and the @ Operator Learn vectors in NumPy with dot, vdot, inner, outer, matmul and the @ operator, matrix shape rules, norms, the angle between vectors and the cross product.
  2. 22 Matrix Operations Learn NumPy matrix operations: transpose, trace, determinant, inverse, matrix_power, block matrices and kron, and why you should rarely invert a matrix.
  3. 23 The Legacy np.matrix Class and Why to Avoid It Compare np.matrix with ndarray: operator differences for * and **, always-2D behaviour, shape surprises, and how to migrate old matrix code to arrays and the @ operator.
  4. 24 Solving Linear Systems and Least Squares Solve linear systems with np.linalg.solve, fit lines with lstsq and polyfit, check conditioning with cond and handle singular matrix errors with NumPy.
  5. 25 Eigenvalues, SVD and Decompositions Learn eigenvalues and eigenvectors, SVD, QR and Cholesky decompositions in NumPy, with low-rank approximation, PCA in a few lines and image compression.
  6. 26 Einstein Summation with einsum and tensordot Learn NumPy einsum notation for matrix multiply, batch matmul, trace and outer products, plus tensordot for higher-dimensional arrays and the optimize flag.

Random Numbers and Statistics

  1. 27 Random Numbers with Generators Generate reproducible random numbers in NumPy 2 with default_rng: random, integers, normal, choice, shuffle, permutation, seeds, and independent streams.
  2. 28 Probability Distributions and Sampling Sample from binomial, Poisson, exponential, beta, gamma and multivariate normal distributions with NumPy, plot histograms, see the CLT and bootstrap.
  3. 29 Statistics, Correlation and Covariance Compute mean, median, mode, standard deviation, covariance and correlation with NumPy, then normalize data, smooth it with a moving average and bin it in 2D.
  4. 30 Monte Carlo Simulations Estimate pi, dice odds, the birthday problem and random walks by simulating millions of trials at once, with confidence intervals and reproducible seeds.

Working with Real Data

  1. 31 Missing Data and NaN Handle missing values in NumPy with np.nan, nan-aware functions, masked arrays, boolean filters, fill strategies and linear interpolation with np.interp.
  2. 32 Structured Arrays and Text Data Store mixed-type records in structured arrays, read CSV text with loadtxt and genfromtxt, process strings with np.char, and compute with datetime64 dates.
  3. 33 Saving and Loading Arrays Save and load NumPy arrays with np.save, savez and savez_compressed, convert to raw bytes with tobytes and frombuffer, compare file sizes and avoid pickle.
  4. 34 Arrays as Images and Plots Treat images as 3D uint8 arrays. Generate gradients, slice color channels, convert to grayscale, flip, crop and threshold, then draw arrays with matplotlib.
  5. 35 Working with Real Images in NumPy Load and save real image files with Pillow, convert them to NumPy arrays, work with channels, crop, flip, mask and resize them, and avoid uint8 and mode traps.
  6. 36 Signals, Convolution and the FFT Learn to build sine waves, find frequency peaks with np.fft.rfft, filter noise, smooth data with np.convolve and avoid windowing and aliasing mistakes.

Performance and Internals

  1. 37 Memory Layout and Strides Understand how NumPy stores arrays in memory: strides, C and Fortran order, contiguity flags, free transposes, sliding_window_view and safe use of as_strided.
  2. 38 Writing Fast NumPy Code Make NumPy code fast: replace Python loops, preallocate, use in-place operations and smaller dtypes, avoid temporaries, measure with timeit and chunk big data.
  3. 39 Advanced Techniques Go beyond the basics: apply_along_axis, frompyfunc, vectorize, ufunc.reduce, accumulate, outer and at, polynomials with poly1d and vander, and cumulative tricks.
  4. 40 Sparse Matrices with SciPy and NumPy Learn when a sparse matrix beats a NumPy array, how scipy.sparse formats (COO, CSR, CSC, LIL, DOK, DIA) store data, and how to convert, multiply and densify them.
  5. 41 Common Pitfalls and Debugging Arrays Debug NumPy like a pro: read shape errors, catch silent broadcasting bugs, integer overflow, view mutation, float equality, ambiguous truth values and NumPy 2 changes.

Projects

  1. 42 Project: Conway's Game of Life Build Conway's Game of Life with NumPy: count neighbors with np.roll, apply the rules in one expression, wrap the edges, run generations and print glider and blinker.
  2. 43 Project: Image Filters from Scratch Build blur, sharpen and edge-detection filters with plain NumPy. Make a synthetic image, slide windows with sliding_window_view, and tune brightness and contrast.
  3. 44 Project: Linear Regression from Scratch Build linear regression with NumPy only. Generate data, solve the normal equation, train with vectorized gradient descent, plot the learning curve, and compare with lstsq.
  4. 45 Project: A Tiny Neural Network Build a two-layer neural network with only NumPy. Write the forward pass, softmax and cross-entropy, backpropagation with matrices, a training loop and a decision boundary plot.
  5. 46 Project: K-Means Clustering Implement k-means clustering in NumPy. Build a distance matrix with broadcasting, update centroids without loops, detect convergence, restart for stability and plot the clusters.

Practice and Review

  1. 47 Practice Exercises Practice NumPy with 20 graded exercises on array creation, indexing, broadcasting, aggregation and linear algebra. Every solution runs live in your browser.
  2. 48 Interview Questions Prepare for data and Python interviews with common NumPy questions on views vs copies, broadcasting, axes, vectorization, dtypes and performance, with runnable answers.
  3. 49 NumPy Cheat Sheet A one-page NumPy 2 cheat sheet with tables for creating arrays, indexing, math, reshaping, linear algebra, random numbers and file I/O, plus runnable examples.