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