Python Reference ยท Third-party Libraries
The NumPy library
Overview of NumPy: creating ndarray objects, shape and dtype, vectorized math, broadcasting, indexing, aggregation, and the most useful functions with examples.
NumPy is the foundation of numerical computing in Python. Its core object is the ndarray: a fixed-size, typed, multi-dimensional grid of numbers stored in one block of memory. Operations on whole arrays run in compiled code, which makes them far faster than Python loops and lets you write math the way you would on paper.
NumPy is not part of the standard library, so on your own machine you install it with python -m pip install numpy. Pandas, SciPy, Matplotlib and scikit-learn all build on it. The live examples below run in the browser.
import numpy as np a = np.array([1, 2, 3]) print(a * 2) # [2 4 6]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Core ideas
Shape and dtype. shape is a tuple with the length of each dimension; dtype is the single element type (int64, float64, bool, and so on). All elements share one dtype, so mixing integers and floats upcasts to float.
Vectorization. a + b, a * 2 and np.sqrt(a) act on every element. Prefer them to loops.
Broadcasting. When shapes differ, NumPy lines them up from the right and stretches dimensions of size 1. A (2, 3) array plus a (3,) array works; a (2, 3) array plus a (2,) array does not, and raises ValueError.
Views and copies. Basic slicing such as a[1:4] returns a view that shares memory with the original, so writing to it changes a. Boolean-mask and integer-list indexing return copies. Call .copy() when you need independence.
Most used functions
| Function or attribute | Purpose |
|---|---|
np.array(obj) |
Build an array from lists or tuples. |
np.zeros, np.ones, np.full, np.empty |
Arrays of a given shape filled with a value. |
np.arange(start, stop, step) |
Like range, but returns an array (floats allowed). |
np.linspace(start, stop, num) |
num evenly spaced values including the end. |
a.reshape(...), a.T, a.ravel() |
Change shape, transpose, flatten. |
np.concatenate, np.vstack, np.hstack |
Join arrays. |
a.sum(), mean, min, max, std, argmax |
Reductions; pass axis= for one direction. |
np.where(cond, x, y) |
Element-wise choice. |
np.dot(a, b) / a @ b |
Dot product and matrix multiplication. |
np.random.default_rng(seed) |
Create a seeded random generator. |
np.allclose(a, b) |
Compare floats with a tolerance. |
Usage notes
- Use
==carefully.a == bon arrays gives an array of booleans, soif a == b:raisesValueErrorfor more than one element. Use(a == b).all()ornp.array_equal(a, b). - Integer overflow wraps silently in fixed-size dtypes such as
int8, unlike Python's unlimitedint. - Floating-point math is approximate. Compare with
np.iscloseornp.allclose. - Random numbers: the modern way is
rng = np.random.default_rng(42)and thenrng.integers(...),rng.random(...). Seed it to get repeatable results. - Lists are not arrays.
[1, 2] * 2repeats the list, butnp.array([1, 2]) * 2multiplies the numbers. - Memory. Arrays of numbers use far less memory than lists of Python objects, but they need a fixed size: appending creates a new array, so build a list first, then convert.
- NumPy 2.x changed some names and scalar printing rules (for example
np.float64(3.0)shows its type inrepr). Useprint()orfloat()if exact output matters.
Related
- pandas, Matplotlib, scikit-learn
array,statistics,math- Lessons: NumPy, Machine learning basics