NumPy Array Addition
In NumPy, adding arrays is one of the most basic and powerful operations.
Instead of using loops, NumPy allows you to add arrays element by element very efficiently.
This is called Array Addition.
What is Array Addition in NumPy?
Array addition means:
Adding corresponding elements of two arrays of the same shape.
Example:
[1, 2, 3] + [4, 5, 6] = [5, 7, 9]
Why Use NumPy Array Addition?
- Faster than Python loops
- Simple syntax
- Works on large datasets
- Supports multi-dimensional arrays
- Used in data science & ML
Basic Array Addition Example
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = a + b
print(result)
Output:
[5 7 9]
How Array Addition Works
NumPy performs element-wise addition:
a = [a1, a2, a3]
b = [b1, b2, b3]
Result = [a1+b1, a2+b2, a3+b3]
Array Addition with 2D Arrays
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6]
])
b = np.array([
[10, 20, 30],
[40, 50, 60]
])
print(a + b)
Output:
[[11 22 33]
[44 55 66]]
Adding Array and Scalar
NumPy supports broadcasting automatically.
import numpy as np
a = np.array([1, 2, 3])
print(a + 10)
Output:
[11 12 13]
Explanation:
-
Scalar
10is expanded to[10, 10, 10] - Then added element-wise
1D vs 2D Addition Example
import numpy as np
a = np.array([1, 2, 3])
b = np.array([[10, 20, 30],
[40, 50, 60]])
print(b + a)
Output:
[[11 22 33]
[41 52 63]]
Rules for Array Addition
Rule 1: Same Shape
Arrays must have same shape OR be broadcastable.
Rule 2: Element-wise Operation
Each element is added individually.
Rule 3: Broadcasting Allowed
Smaller arrays are expanded automatically.
Array Addition vs Python List
❌ Python List:
[1, 2, 3] + [4, 5, 6]
Result:
[1, 2, 3, 4, 5, 6] # concatenation
✅ NumPy Array:
np.array([1,2,3]) + np.array([4,5,6])
Result:
[5 7 9]
Real-World Use Cases
Array addition is used in:
- Image brightness adjustment
- Data normalization
- Neural network computations
- Sensor data processing
- Financial calculations
Example: Image Brightness Increase
image = image + 50
✔ Adds brightness to all pixels
✔ No loops required
✔ Very fast execution
Advantages of Array Addition in NumPy
- Fast performance
- Simple syntax
- Works with large datasets
- Supports broadcasting
- Essential for data science
Summary
NumPy array addition is an element-wise operation that allows fast and efficient computation between arrays.
It is a core feature of NumPy and is widely used in data processing and machine learning with Python.
Conclusion
Mastering array addition helps you understand how NumPy handles vectorized operations efficiently, making your code faster and cleaner.


0 Comments