A ufunc runs the same math on every cell. For this chapter, both sides have the same shape (or a scalar). Stretching shapes is the next chapter.
Goal
Use +, *, np.sqrt, np.round, np.clip, and np.maximum on matching arrays.
Scalars and same-shape arrays
# Rows: Nairobi, Mombasa, Kisumu · cols: A, B, C
units = np.array(
[
[12, 7, 2],
[9, 6, 0],
[3, 11, 1],
],
dtype=float,
)
print(units * 2)
print()
print(units + units)sqrt, round, clip
units = np.array(
[
[12, 7, 2],
[9, 6, 0],
[3, 11, 1],
],
dtype=float,
)
print(np.sqrt(units))
print()
print(np.round(np.sqrt(units), 2))
print()
print(np.clip(units, 1, 10))maximum / minimum
left = np.array([12, 7, 2], dtype=float)
right = np.array([9, 6, 8], dtype=float)
print(np.maximum(left, right))
print(np.minimum(left, right))Elementwise — not “the max of the whole array”. For that, use np.max (Reduce chapter).
np.where with two arrays
units = np.array([[12, 7, 2], [9, 6, 0]], dtype=float)
alt = np.zeros_like(units)
print(np.where(units >= 9, units, alt))Tip
If units * prices raises operands could not be broadcast, the shapes differ. Finish this chapter with matching shapes, then open Broadcasting.