Skip to content
Justice Tech School

NumPy Tutorial

Fast arrays and math for data science in Python.

Start learning NumPy
Getting started7 lessons
  1. 1NumPy IntroductionNumPy is the base library for numerical computing in Python.
  2. 2NumPy Get StartedInstall with pip install numpy, then import numpy as np.
  3. 3Why NumPy is FastOperations on arrays run in compiled code and avoid Python loop overhead.
  4. 4Creating Arraysnp.array converts a list.
  5. 5Array Attributesndim, shape, size, dtype and itemsize describe an array.
  6. 6Data TypesEvery array has one dtype such as int64, float64, bool or U5 for strings.
  7. 7Random NumbersUse a Generator from default_rng with a seed for repeatable results.
Arrays20 lessons
  1. 8Copies and ViewsSlices are views that share memory with the original.
  2. 9Reshapereshape changes the shape without changing the data.
  3. 10Flatten and Transposeravel and flatten make 1D arrays.
  4. 11Joining Arraysconcatenate joins along an existing axis.
  5. 12Splitting Arrayssplit divides an array into equal parts or at given indexes.
  6. 13Sorting and Searchingsort returns a sorted copy.
  7. 14Unique Values and Countsnp.unique returns sorted unique values and can count them.
  8. 15dtype and Type ConversionEvery array has one dtype such as int64 or float64.
  9. 16Array Attributesshape, ndim, size, dtype and itemsize describe an array.
  10. 17zeros, ones, full and emptyCreate filled arrays of a given shape.
  11. 18arange and linspacearange steps by size and linspace gives a count of evenly spaced values.
  12. 19Random NumbersUse a Generator with a seed for repeatable random data.
  13. 20Arrays from Listsnp.array turns nested lists into arrays.
  14. 21Copies and ViewsSlices are views that share memory.
  15. 22concatenate, stack and splitJoin arrays along an axis, stack new ones and split into parts.
  16. 23sort, argsort and uniquesort orders values, argsort gives the order and unique finds distinct values.
  17. 24Lists versus ArraysArrays hold one type, use less memory and do math on whole collections.
  18. 25argmax along axesargmax and argmin accept an axis to find positions per row or column.
  19. 26Counting with Maskscount_nonzero counts True values quickly.
  20. 27Iterating Arraysnditer and ndenumerate visit every element.
Indexing24 lessons
  1. 28Array IndexingUse zero based indexes.
  2. 29Slicingstart:stop:step selects ranges.
  3. 30Boolean IndexingA comparison creates a boolean mask.
  4. 31Fancy IndexingPass a list of indexes to pick several elements in any order.
  5. 32where, select and clipnp.where picks between two values by condition.
  6. 33Changing ValuesAssign to an index, slice or mask to update many elements at once.
  7. 34Indexing and SlicingUse [i], [i, j] and slices start:stop:step.
  8. 35Boolean IndexingA boolean mask selects the True items.
  9. 36Fancy IndexingPass a list of positions to pick several items in any order.
  10. 37wherewhere finds positions or picks between two values by a condition.
  11. 38Assigning ValuesSlices and masks can be assigned directly.
  12. 39take, put and compresstake picks by index and compress filters by a condition array.
  13. 40Slicing Rows and Columnsa[rows, cols] works with slices.
  14. 41Diagonals and Trianglesdiag extracts or builds diagonals.
  15. 42Structured ArraysA structured dtype stores named fields, like a tiny table.
  16. 43Masked ArraysMasked arrays ignore invalid entries in calculations.
  17. 44Saving and Loadingsave and load keep arrays in .npy files.
  18. 45Print Optionsset_printoptions controls precision, threshold and suppress.
  19. 46Vectorising CodeReplace Python loops with array operations for speed and clarity.
  20. 47Set Operationsunion1d, intersect1d, setdiff1d and in1d work on arrays like sets.
  21. 48meshgridmeshgrid builds coordinate grids from two vectors.
  22. 49Practice: Normalise DataScale values to 0 to 1 and standardise with the mean and std.
  23. 50Practice: Moving AverageUse convolution to smooth values.
  24. 51Practice: Grade MatrixCombine aggregation, broadcasting and boolean masks.
Math and statistics22 lessons
  1. 52Array ArithmeticOperators work element by element on arrays of the same shape: + - * / ** and %.
  2. 53Universal Functionsufuncs such as sqrt, exp, log, sin and abs apply to every element quickly.
  3. 54Aggregationssum, mean, min, max, std and var summarise an array.
  4. 55Statisticsmedian, percentile, std, var and corrcoef describe data.
  5. 56Cumulative Operationscumsum and cumprod give running totals.
  6. 57Rounding and Precisionround, floor, ceil and trunc handle decimals.
  7. 58Missing Values: NaNNaN marks missing numbers.
  8. 59Element-wise MathOperators and ufuncs work on every item without loops.
  9. 60sum, mean, min, max and axesAggregations reduce an array.
  10. 61Statisticsmedian, std, var, percentile and corrcoef summarise data.
  11. 62Cumulative Operationscumsum, cumprod and diff track running totals and changes.
  12. 63Roundinground, floor, ceil and trunc change decimals.
  13. 64Handling NaNNaN marks missing values.
  14. 65Comparing Arraysallclose compares with tolerance, array_equal checks exact equality and any and all combin.
  15. 66Sorting Along an Axissort works along an axis.
  16. 67Histograms and Binshistogram counts values in bins and digitize assigns bin numbers.
  17. 68Trigonometry and Constantssin, cos, tan, pi and degrees work on arrays in radians.
  18. 69Logs and Exponentialslog, log2, log10 and exp are ufuncs.
  19. 70clip, minimum and maximumclip limits values and minimum and maximum compare two arrays element-wise.
  20. 71Weighted Averagesaverage supports weights.
  21. 72Random DistributionsGenerators draw from normal, uniform and other distributions.
  22. 73Shuffle and Permutationpermutation returns a shuffled copy and shuffle changes in place.
Shapes11 lessons
  1. 74BroadcastingBroadcasting lets arrays of different shapes work together when dimensions match or are 1.
  2. 75Adding Axesnp.newaxis or None adds a length 1 dimension.
  3. 76Grids with meshgridmeshgrid builds coordinate matrices from vectors, handy for plotting functions of two vari.
  4. 77Repeat and Tilerepeat repeats each element and tile repeats the whole array.
  5. 78Working With AxesMany functions take axis.
  6. 79reshape and -1reshape changes the shape without changing data.
  7. 80flatten, ravel and Tflatten copies to 1D, ravel returns a view when possible and T transposes.
  8. 81Adding Axesnewaxis or reshape adds a dimension, useful for broadcasting.
  9. 82Broadcasting RulesArrays with different shapes work together when each dimension matches or is 1.
  10. 83squeeze and swapaxessqueeze removes length 1 axes and swapaxes exchanges two axes.
  11. 84tile and repeatrepeat repeats elements and tile repeats the whole array.
Linear algebra16 lessons
  1. 85Dot Product and Matrix MultiplicationUse @ or np.dot for matrix multiplication.
  2. 86Determinant and Inversenp.linalg.det and np.linalg.inv work on square matrices.
  3. 87Solving Linear Equationsnp.linalg.solve finds x in Ax = b.
  4. 88Eigenvalues and Eigenvectorseig returns eigenvalues and eigenvectors.
  5. 89Norms and Distancesnp.linalg.norm measures vector length.
  6. 90Special Matriceseye makes an identity matrix, diag builds or extracts diagonals, triu and tril keep the up.
  7. 91Singular Value DecompositionSVD splits a matrix into U, S and Vt.
  8. 92Dot Product and Matrix Productdot and @ multiply matrices.
  9. 93Inverse and Determinantlinalg.inv inverts a square matrix and det gives the determinant.
  10. 94Solving Linear Equationslinalg.solve finds x in A x = b without computing the inverse.
  11. 95Eigenvalueslinalg.eig finds eigenvalues and eigenvectors of a square matrix.
  12. 96Norms and Distancelinalg.norm measures vector length.
  13. 97Outer and Cross Productsouter builds a table of products and cross gives a perpendicular 3D vector.
  14. 98Matrix Power and Rankmatrix_power repeats a matrix product and matrix_rank counts independent rows.
  15. 99einsum Introductioneinsum writes sums over axes in a short notation.
  16. 100Least Squares Fitlstsq fits the best line through noisy points.
Advanced NumPyPremium11 lessons
  1. 101Structured ArraysA structured dtype stores named fields, like a table row, in one array.
  2. 102Masked Arraysnumpy.ma hides invalid entries so statistics ignore them without changing the data.
  3. 103einsumeinsum writes tensor operations with index notation: sums, dot products, traces and matrix.
  4. 104Strides and Memory LayoutStrides say how many bytes to jump to reach the next element in each axis.
  5. 105vectorize and apply_along_axisnp.vectorize wraps a Python function so it accepts arrays.
  6. 106Saving and Loadingnp.save writes one array in .npy format, np.savez several arrays, and np.loadtxt reads tex.
  7. 107Polynomials and Fittingnp.polyfit fits a polynomial to points and np.polyval evaluates it.
  8. 108Interpolation and Gradientsnp.interp does linear interpolation.
  9. 109Fourier Transformnp.fft turns signals into frequencies.
  10. 110Set Operationsintersect1d, union1d, setdiff1d and setxor1d treat arrays as sets and return sorted unique.
  11. 111Histograms and Binningnp.histogram counts values per bin.
NumPy in practicePremium12 lessons
  1. 112Performance TipsPrefer vectorized code, avoid Python loops over arrays, use appropriate dtypes, preallocat.
  2. 113Saving Memory with dtypesSmaller dtypes such as int8, float32 and bool save memory.
  3. 114Images as ArraysAn image is an array of pixels: height by width by channels.
  4. 115Monte Carlo EstimationSimulate many random samples to estimate a value.
  5. 116Normalising DataMachine learning often scales features: min max to 0 to 1, or z score to mean 0 and standa.
  6. 117Linear Regression with NumPyLeast squares solves for the line that best fits noisy points.
  7. 118PCA from ScratchPrincipal component analysis centres the data, computes the covariance matrix and takes it.
  8. 119Game of LifeVectorized neighbour counting with slicing and roll shows how array thinking replaces nest.
  9. 120NumPy with pandas and Plottingpandas columns are NumPy arrays under the hood.
  10. 121Testing Numerical CodeNever compare floats with ==.
  11. 122NumPy Best PracticesThink in whole arrays, check shapes often, keep dtype consistent, avoid hidden copies, nam.
  12. 123Next StepsYou can now handle arrays, math, linear algebra and performance.