NumPy Arrays
NumPy (Numerical Python) gives Python a fast, compact way to store and calculate with large collections of numbers. Its core object, the array, is the foundation that pandas, Matplotlib, SciPy and scikit-learn are all built on.
Why not just use lists?
A Python list can hold anything, which makes it flexible but slow for maths. A NumPy array holds items of one type packed tightly in memory, so NumPy can run calculations in optimised compiled code. On large datasets, array maths is often tens of times faster than a loop over a list, and it needs far less code.
import numpy as np nums_list = [1, 2, 3] nums_array = np.array([1, 2, 3]) print(nums_list * 2) # repeats the list print(nums_array * 2) # multiplies every element print(nums_list + [10]) # joins two lists print(nums_array + 10) # adds 10 to every element
Notice the printing style: lists show commas, while arrays print their values separated only by spaces.
Creating an array
Pass a list to np.array(). Every array has a dtype (data type) that all its elements share.
import numpy as np prices = np.array([120, 85, 250, 60]) # KES print(prices) print(type(prices)) print(prices.dtype)
NumPy pads numbers to the same width when printing, which is why there are two spaces before 85. The type is ndarray, short for "n-dimensional array".
Mixed values are converted to one type
print(np.array([1, 2.5, 3])) # ints become floats print(np.array([1, "two"])) # everything becomes text print(np.array([1, "two"]).dtype)
Floats print with a trailing dot (1. means 1.0). <U21 means Unicode text of up to 21 characters. Text arrays can't do maths, so watch out for numbers that arrive as strings.
Two-dimensional arrays
A list of lists becomes a 2-D array, like a table with rows and columns. Here, each row is a shop branch and each column a product.
units = np.array([[30, 12, 8],
[25, 20, 15]])
print(units)
print(units.shape) # (rows, columns)
print(units.ndim) # number of dimensions
print(units.size) # total number of elements
units array has 2 rows and 3 columns. Axis 0 runs down the rows and axis 1 runs across the columns, matching the order of numbers in shape.| Attribute | Meaning |
|---|---|
shape | Size along each dimension, as a tuple |
ndim | Number of dimensions (1 for a row of values, 2 for a table) |
size | Total number of elements |
dtype | Type of every element, e.g. int64, float64, bool |
Built-in ways to create arrays
print(np.zeros(3)) # three 0.0 values print(np.ones((2, 3))) # 2 rows, 3 columns of 1.0 print(np.full(3, 7)) # three 7s print(np.arange(0, 10, 2)) # like range(): start, stop, step print(np.linspace(0, 1, 5)) # 5 evenly spaced values from 0 to 1 print(np.arange(6).reshape(2, 3))
arange() excludes the stop value, just like range(). linspace() includes both ends and lets you choose how many values you want. reshape() rearranges the same values into a new shape; the total size must stay the same (6 values fit a 2 × 3 shape, not 4 × 2).
Choosing and changing the dtype
a = np.array([1, 2, 3], dtype=np.float64) print(a) b = np.array([2.9, 4.1, 5.5]).astype(int) # cuts off the decimals print(b)
Converting floats to integers truncates (cuts off) the decimals; it doesn't round. 2.9 becomes 2. The same happens if you put a float into an integer array: after a = np.array([1, 2, 3]) and a[0] = 2.7, the array is [2 2 3]. Use np.round() first if you want rounding.
np.array(1, 2, 3) raises a TypeError. The values must be passed as one list: np.array([1, 2, 3]).
Key points
- A NumPy array stores many values of one type and supports fast, whole-array maths.
- Create arrays with
np.array(),zeros(),ones(),arange()andlinspace(). shape,ndim,sizeanddtypedescribe an array.- Next, learn to calculate with arrays in Array Operations.
Tip: use the ← and → keys to move between pages.
