NumPy Arrays
Python · NumPy Library
Theory
NumPy is the core library for numerical computing in Python, and its central object is the ndarray (n-dimensional array). Every element has the same data type (dtype) and the values sit side by side in one block of memory, which is why maths on arrays runs in fast compiled code. np.array([100, 250, 300]) turns a list into a 1-D array; a list of lists gives a 2-D array.
NumPy also builds arrays for you. np.arange(0, 10, 3) works like range and gives [0, 3, 6, 9] (the stop value is excluded). np.linspace(0, 100, 5) gives 5 evenly spaced values including both ends. np.zeros(3), np.ones((2, 3)) and np.full((2, 2), 7) fill an array of a given shape, and np.eye(3) is the identity matrix. Check any array with .shape, .ndim, .dtype and .size.
Why we use it
Python lists are flexible but slow for maths on large amounts of numbers. NumPy arrays store numbers compactly and run element-wise maths fast, and they are the shared format that pandas, scikit-learn and matplotlib use underneath.
When to use it
Use arrays for numeric data: measurements, matrices, model inputs and pixels. Use arange when you know the step, linspace when you know how many points you need. For labelled or mixed-type columns use a pandas DataFrame instead.
How it works
- import numpy as np
- Do you already have the values in a list? Yes: np.array(list). No: Build one with a creation function.
- Know the step size? Yes: np.arange(start, stop, step). No: np.linspace(start, stop, num).
- Need a blank array? np.zeros / np.ones / np.full(shape, value)
- Check .shape, .ndim and .dtype
- Array ready for vectorised maths
Syntax
import numpy as np
np.array([1, 2, 3])
np.arange(start, stop, step)
np.linspace(start, stop, num)
np.zeros(shape) np.ones(shape) np.full(shape, value) np.eye(n)Example
import numpy as np
sales = np.array([100, 250, 300])
grid = np.zeros((2, 3))
print(sales.shape, grid.shape)Key points
- All elements share one dtype, unlike a list
- arange excludes the stop value; linspace includes it
- zeros and ones give float64 arrays unless you pass dtype=
- Shapes are tuples: np.zeros((2, 3)) needs the inner brackets
- shape, ndim, dtype and size describe any array