๐ 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.