NumPy: Arrays and Vectorized Computation

First lesson of the Data Analysis with pandas and NumPy course, free to read: about 15 minutes, 3 exercises and 3 quiz questions. This is the catalogue's base lesson; in the student space, it is rewritten for your profile.

Objectives

  • Create NumPy arrays and know their attributes (shape, dtype)
  • Perform vectorized calculations without loops
  • Filter an array with a boolean mask and compute statistics

ndarray arraysVectorized computationBoolean masks

NumPy: arrays and vectorized computation

NumPy is the numerical computing library on which pandas, scikit-learn and most data tools in Python are built. Its basic building block is the array (ndarray): a grid of values of a single type, stored compactly in memory.

Creating an array

import numpy as np   # universal alias

prix = np.array([49.0, 19.0, 189.0, 25.5])
print(prix.shape)    # (4,)     : 4 elements in one dimension
print(prix.dtype)    # float64  : all elements have the same type

np.arange(0, 10, 2)  # array([0, 2, 4, 6, 8])
np.zeros(3)          # array([0., 0., 0.])
np.linspace(0, 1, 5) # 5 evenly spaced values between 0 and 1

Computing without loops: vectorization

With a list, applying VAT requires a loop or a comprehension. With NumPy, you write the operation directly on the array:

prix_ttc = prix * 1.2        # each element is multiplied
quantites = np.array([3, 10, 1, 4])
ca = prix * quantites        # element-by-element multiplication
print(ca.sum())              # 628.0

This vectorized calculation runs in compiled code: on a million values, it is dozens of times faster than a Python loop. Combining an array and a plain number (prix * 1.2) is called broadcasting: NumPy “stretches” the number to the size of the array.

Be careful: with a list, [1, 2] * 2 gives [1, 2, 1, 2] (repetition), whereas with NumPy np.array([1, 2]) * 2 gives [2, 4].

Filtering with a boolean mask

A comparison on an array returns an array of booleans, called a mask:

masque = prix > 30
print(masque)              # [ True False  True False]
print(prix[masque])        # [ 49. 189.]  : only the Trues are kept
print(prix[(prix > 20) & (prix < 100)])   # [49.  25.5]
print(masque.sum())        # 2 : True counts as 1

To combine conditions, use & (and), | (or), ~ (not) and put each condition in parentheses. The and / or keywords do not work on arrays.

Two-dimensional arrays and axis

# ventes: 3 stores (rows) x 4 quarters (columns)
ventes = np.array([[10, 12, 9, 14],
                   [ 8,  7, 11, 10],
                   [15, 14, 13, 18]])
print(ventes.shape)          # (3, 4)
print(ventes[0, 2])          # 9 : row 0, column 2
print(ventes.sum(axis=1))    # [45 36 60] : total per store (the columns are collapsed)
print(ventes.mean(axis=0))   # average per quarter (the rows are collapsed)
print(ventes.max())          # 18 : over the whole array

Remember: axis=0 aggregates along the rows (one result per column), axis=1 aggregates along the columns (one result per row).

Key takeaways

  • A NumPy array has a single type and a shape (shape).
  • Operations are vectorized: no loop.
  • Filter with masks and &, |, ~ in parentheses.

Exercises

Solutions and tests stay on the server. In the student space, your code is run and checked, and the tutor gives hints before the solution.

  1. CodeDifficulty 1Python in the browser2 hints

    Vectorized revenue calculation

    From the arrays prix and quantites:

    • ca: the array of revenue per product;
    • ca_total: the total sum;
    • nb_gros: the number of products whose revenue is strictly above 100;
    • ca_gros: the array of revenues above 100.

    Do not use any loops.

    import numpy as np
    
    prix = np.array([49.0, 19.0, 189.0, 12.5, 75.0])
    quantites = np.array([3, 10, 1, 4, 2])
    
    ca = ...
    ca_total = ...
    nb_gros = ...
    ca_gros = ...
  2. CodeDifficulty 2Python in the browser2 hints

    Statistics by axis

    notes contains the grades of 4 students (rows) on 3 assessments (columns).

    Compute:

    • moy_eleves: each student’s average (array of 4 values);
    • moy_evals: each assessment’s average (3 values);
    • nb_admis: the number of students whose average is ≥ 10;
    • notes_bonus: the grades increased by 1 point, capped at 20 (np.minimum).
    import numpy as np
    
    notes = np.array([[12, 9, 15],
                      [8, 7, 10],
                      [19, 18, 20],
                      [10, 11, 9]])
    
    moy_eleves = ...
    moy_evals = ...
    nb_admis = ...
    notes_bonus = ...
  3. Multiple choiceDifficulty 21 hint

    Combining conditions

    Which expression selects the values of a between 10 and 20 (exclusive)?

    • a[a > 10 and a < 20]
    • a[(a > 10) & (a < 20)]
    • a[a > 10 & a < 20]
    • a[10 < a < 20]

End-of-lesson quiz

  1. What is np.array([1, 2, 3]) * 2?

    • [1, 2, 3, 1, 2, 3]
    • array([2, 4, 6])
    • An error
  2. On an array of shape (3, 4), what shape does t.sum(axis=0) have?

    • (3,)
    • (4,)
    • (3, 4)
  3. What does (np.array([5, 15, 25]) > 10).sum() return?

    • 2
    • 40
    • True

The rest of the course

  1. pandas: Series, DataFrame and Reading Data15 min
  2. Select, Filter and Sort20 min
  3. Create and Transform Columns20 min
  4. Aggregating: groupby and Pivot Tables20 min
  5. Combining Tables: merge and concat20 min

Data Analysis with pandas and NumPy · Intermediate · 3 h 20 min