Arrays and the ndarray
The bookshop logged how many copies each sale moved: 3, 5, 2, 4, 1, 6, 2, 3. A Python list can hold these, but it treats each number as a separate object. NumPy packs them into one tight block of memory of a single type, which is why data tools built on it are fast.
The rule
An array is one type, one shape, many values.
import numpy as np
copies = np.array([3, 5, 2, 4, 1, 6, 2, 3])
copies.dtype # dtype('int64')
copies.shape # (8,)
copies.ndim # 1- dtype is the single type every element shares, such as
int64,float64orbool. - shape is a tuple giving the length along each dimension.
(8,)means one dimension of 8 values. - ndim is the number of dimensions, which is the length of
shape.
Because there is only one dtype, NumPy converts mixed input to a type that can hold everything. Mixing integers with a float gives floats: np.array([1, 2.5]) has dtype float64, and the 1 becomes 1.0.
Arrays can have more than one dimension. Split the eight sales into two rows of four days:
grid = copies.reshape(2, 4)
# [[3 5 2 4]
# [1 6 2 3]]
grid.shape # (2, 4)
grid.ndim # 2
grid.size # 8reshape rearranges the same values; the total count must stay the same. 2 × 4 = 8 works, 3 × 3 would fail.
Handy starting arrays: np.zeros(4), np.ones((2, 3)), and np.arange(0, 10, 2), which gives [0 2 4 6 8] (the stop value is left out, just like range).