Skip to the workspace
Pebellslearn by building
NumPy Arrays  ›  Lesson

Array Operations

Array Operations 14 minArithmetic and comparisons on arrays work element by element, a single number is broadcast to every element, and aggregations collapse an axis.

python data analysis / Array Operations

Explore each scene at your own pace.

01 · The rule

The rule

Array Operations

To get revenue for each of the eight sales with plain lists, you would write a loop that multiplies copies by price one pair at a time. With NumPy you write copies * price and it is done, for eight values or eight million. Thinking in whole arrays instead of loops is the first real habit of data analysis.

The rule

Operators work element by element; a single number stretches to fit.

copies = np.array([3, 5, 2, 4, 1, 6, 2, 3])
price  = np.array([250, 400, 400, 250, 250, 120, 120, 400])

revenue = copies * price
# [ 750 2000  800 1000  250  720  240 1200]

Two arrays of the same shape are combined position by position: first with first, second with second. This is called vectorised arithmetic, and it runs in fast compiled code rather than a Python loop.

When one side is a single number, NumPy broadcasts it: the number is reused against every element.

price * 1.18      # add 18% tax to every price
copies + 1        # [4 6 3 5 2 7 3 4]
copies > 3        # [False  True False  True False  True False False]

Comparisons are element-wise too, giving an array of booleans you will soon use for filtering.

Aggregations collapse an array to a summary:

revenue.sum()     # 6960
copies.mean()     # 3.25
copies.max()      # 6
copies.argmax()   # 5, the position of the largest value

On a 2-D array, axis chooses the direction. With grid = copies.reshape(2, 4):

grid.sum(axis=0)  # [ 4 11  4  7]  one total per column
grid.sum(axis=1)  # [14 12]        one total per row
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.