LearnWave
Learn it. Master it.

Introduction to NumPy

Creating arrays

Create an array and describe it with ndim, shape and size.

Creating arrays with np.array():

  • 1-D from a list: array1 = np.array([10, 20, 30]).
  • If the list mixes types, all values are promoted to one type. With a string present, everything becomes a string: np.array([5, -7.4, 'a', 7.2]) gives elements '5', '-7.4', 'a', '7.2' with dtype '<U32' (a Unicode string of up to 32 characters).
  • 2-D from nested lists: np.array([[2.4, 3], [4.91, 7], [0, -1]]) has 3 rows and 2 columns.

Attributes of an ndarray:

  • ndim: the number of dimensions (axes), also called the rank.
  • shape: the size of each dimension, as a tuple: (rows, columns), such as (3, 2).
  • size: the total number of elements (rows × columns for 2-D).
  • dtype: the element type: int32, int64, float32, float64, U32 and so on.
  • itemsize: bytes per element. 32 bits = 4 bytes, so int32 and float32 have itemsize 4; int64 and float64 have 8.

Other ways to create arrays:

  • dtype=float inside np.array() converts the values, e.g. integers to floats.
  • np.zeros((3, 4)) makes a 3 × 4 array of zeros; np.ones((3, 2)) an array of ones. Their default type is float.
  • np.arange() works like range() but returns an array: np.arange(6) gives [0, 1, 2, 3, 4, 5]; np.arange(-2, 24, 4) gives [-2, 2, 6, 10, 14, 18, 22].
  • Values are passed as one list: np.array([1, 2, 3, 4]), not np.array(1, 2, 3, 4).

Example (new): seats = np.zeros((4, 5)) could stand for a cinema's 4 rows of 5 seats, all empty: seats.ndim is 2, seats.shape is (4, 5), seats.size is 20, and seats.dtype is float64, so seats.itemsize is 8.

shape is rows × columns; size is their product.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.