Broadcasting, vectorization, and reductions

2.5.5

Apply element-wise operations and summarize over a chosen axis.

On this page

Element-wise calculations

Array arithmetic applies operations element by element. The * operator multiplies matching elements. Use @ or matmul for matrix multiplication.

import numpy as np

quantity = np.array([2, 4, 3])
price = np.array([1.5, 2, 4])
print((quantity * price).tolist())
Example output
[3.0, 8.0, 12.0]

Align shapes from the right

NumPy compares dimensions starting from the right. Two dimensions are compatible when equal or when one is 1. Missing leading dimensions are treated as 1. Use a new axis when aligning a column vector with a matrix.

import numpy as np

marks = np.array([[50, 60], [65, 70]])
print((marks + [5, 3]).tolist())
print(marks.sum(axis=0).tolist())
Adding [5, 3] to each of two marks rows produces [55, 63] and [70, 73]. Download image
The length-2 vector matches the last dimension of the matrix.
Example output
[[55, 63], [70, 73]]
[115, 130]

Reduce one axis

In a rows-by-columns array, sum(axis=0) combines rows and returns one value per column. sum(axis=1) combines columns and returns one value per row. keepdims=True retains the reduced axis with length 1.

import numpy as np

marks = np.array([[50, 60], [65, 70]])
print(marks.sum(axis=0).tolist())
print(marks.sum(axis=1).tolist())
print(marks.sum(axis=0, keepdims=True).shape)
Summing four marks by axis 0 gives [115, 130]. Summing by axis 1 gives [110, 135]. Download image
axis=0 returns one total per column and axis=1 returns one total per row.
Example output
[115, 130]
[110, 135]
(1, 2)

Official references