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).
The shortcut
Read shape as "rows, then columns", and check that the product of the numbers equals the number of values. That one multiplication answers most reshape questions instantly.
Count the values
copies.sizeis 8.
The trap: np.array([1, 2, "3"]) does not raise an error. It quietly turns every value into text, and arithmetic on it will fail later. Always glance at dtype after building an array.
Drills
Answer fast — trust the rule.
What is np.array([[1, 2, 3], [4, 5, 6]]).shape?
What dtype does np.array([4, 7, 1.5]) get?
Which reshape of the 8-value copies array raises an error?
What does np.arange(1, 7, 2) produce?
Remember
- An array is one type, one shape, many values: check
dtypeandshapefirst. - Shape reads rows, then columns; a reshape works only if the numbers multiply to
size. - Mixed input is silently converted to one dtype, sometimes to text.
