Vector Operations
Do math on a whole array at once with vectorization, scalar broadcasting, and comparisons that build a boolean array.
Say you've got a million product prices and you need to add 20% tax to every one. The Python you know says: write a for loop, touch each price, multiply, store it back. That works... and it crawls π β Python re-checks the type of every single number as it goes.
NumPy's answer is vectorization (gloss: writing one operation that applies to EVERY element of an array at once, run in fast compiled C code instead of a Python loop):
import numpy as np
prices = np.array([10, 20, 30])
print(prices * 1.2) # [12. 24. 36.]No loop. You wrote prices * 1.2 once, and NumPy stamped that multiply onto all three numbers. On a million prices it's the same one line β and it flies π.
What does this print?
import numpy as np
arr = np.array([1, 2, 3])
print(arr * 10)- A[10 20 30]
- B[1 2 3 1 2 3 ... ] (repeated 10 times)
- C30
- DError: can't multiply an array by an int
You can also combine two arrays β but they pair up element-wise (gloss: position 0 with position 0, position 1 with position 1, and so on):
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b) # [11 22 33]
print(a ** 2) # [1 4 9]a + b adds matching positions; a 2 squares every element. The two arrays must have the same shape** (the row of lengths from the shapes lesson) β pairing needs a partner for each slot.a = np.array([2, 4, 6]) and b = np.array([1, 1, 1]). What is a + b?- A[3 5 7]
- B[2 4 6 1 1 1]
- C[12 12 12]
- D13
What does this print?
import numpy as np
temps = np.array([20, 25, 30])
print(temps - 5)- A[15 20 25]
- B[20 25 30 -5]
- C15
- D[15]
One more superpower, and it sets up the next few lessons. A comparison applied to an array doesn't give one True/False β it gives a boolean array (gloss: an array of True/False, one per element, from testing each one):
scores = np.array([40, 75, 90])
print(scores > 50) # [False True True]Each element got tested against 50 on its own. Hold onto this β in the boolean-indexing lesson you'll feed an array like this back in to pick out just the elements you want.
What does this print?
import numpy as np
arr = np.array([1, 2, 3])
print(arr > 1)- A[False True True]
- B[True True True]
- CTrue
- D[2 3]
Fill the blank so every price gets 20% tax added at once, with no loop:
prices = np.array([10, 20, 30])
with_tax = prices ___ 1.2- Vectorization applies one operation to EVERY element at once in fast C code β no Python loop
- Arithmetic with a scalar broadcasts it:
arr * 1.2stamps the operation onto each element and returns a new array - Two arrays combine element-wise (position by position) and must share the same shape:
a + b,a ** 2 - A comparison like
arr > 1returns a boolean array β oneTrue/Falseper element
Next up: reductions β turning a whole array of numbers into a single answer (a sum, a mean) and choosing which way to sweep with the axis parameter.