Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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

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.

Can the sales be reshaped to (4, 2)?Step 1 of 4
  1. Count the values

    copies.size is 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.

quick drill

What is np.array([[1, 2, 3], [4, 5, 6]]).shape?

quick drill

What dtype does np.array([4, 7, 1.5]) get?

quick drill

Which reshape of the 8-value copies array raises an error?

quick drill

What does np.arange(1, 7, 2) produce?

Remember

  • An array is one type, one shape, many values: check dtype and shape first.
  • 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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainList or array?

Explain the difference between the list [3, 5, 2, 4] and np.array([3, 5, 2, 4]), and what dtype and shape would be for the array. Then say what happens if you build np.array([3, 5, 2.5, 4]).