π Introduction
If you want to truly master NumPy, you must understand broadcasting.
It allows NumPy to perform operations on arrays of different shapes without using loops.
π What is Broadcasting?
Broadcasting is a technique where NumPy:
- Expands smaller arrays
- Matches them with larger arrays
- Performs element-wise operations
π Automatically, without copying data!
π§ͺ Simple Example
import numpy as npa = np.array([1, 2, 3])
b = 2print(a * b)
π Output:
[2 4 6]
β Here, scalar 2 is broadcasted to match the array.
π Example with Two Arrays
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])print(a + b)
π Output:
[11 22 33]
β Same shape β direct operation
π Broadcasting with Different Shapes
a = np.array([[1], [2], [3]])
b = np.array([10, 20, 30])print(a + b)
π Output:
[[11 21 31]
[12 22 32]
[13 23 33]]
β NumPy expands arrays automatically
π Broadcasting Rules (Important)
NumPy follows these rules:
- Compare shapes from right to left
- Dimensions must be:
- Equal OR
- One of them is 1
- Otherwise β Error β
β οΈ Example of Error
a = np.array([1, 2, 3])
b = np.array([1, 2])print(a + b)
π β Error due to incompatible shapes
β‘ Why Broadcasting is Powerful?
Using NumPy, broadcasting:
- Eliminates loops
- Improves performance
- Reduces memory usage
π¦ Real-World Use Case
prices = np.array([100, 200, 300])
tax = np.array([0.1])final_price = prices + prices * tax
print(final_price)
π Output:
[110. 220. 330.]
β Used in:
- Data science
- Machine learning
- Financial calculations
π Works with Other Libraries
Broadcasting is heavily used in:
- Pandas
- TensorFlow
- Scikit-learn
π Summary Table
| Case | Result |
|---|---|
| Scalar + Array | Broadcast scalar |
| Same shape arrays | Direct operation |
| Different shapes | Auto expansion |
π§ Pro Tips
- Always check array shapes before operations
- Use broadcasting to replace loops
- Combine with vectorization for best performance
π Conclusion
Broadcasting in NumPy is a game-changing feature that makes data operations faster and cleaner.