Skip to the workspace
Pebellslearn by building
NumPy Arrays  ›  Lesson

Arrays and the ndarray

Arrays & ndarray 12 minA NumPy array holds many values of one type in a fixed shape, described by its dtype, shape and number of dimensions.

python data analysis / Arrays and the ndarray

Explore each scene at your own pace.

01 · The rule

The rule

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, float64 or bool.
  • 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       # 8

reshape 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).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.