Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to add a vector to a given Numpy array?
In this problem, we have to add a vector/array to a numpy array. We will define the numpy array as well as the vector and add them to get the result array using NumPy's broadcasting capabilities.
Algorithm
Step 1: Define a numpy array. Step 2: Define a vector. Step 3: Add vector to each row of the original array using broadcasting. Step 4: Print the result array.
Method 1: Using Broadcasting (Recommended)
NumPy automatically broadcasts the vector to each row ?
import numpy as np
original_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
print("Original Array:")
print(original_array)
vector = np.array([1, 1, 0])
print("\nVector:", vector)
# Simple broadcasting addition
result = original_array + vector
print("\nResult:")
print(result)
Original Array: [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] Vector: [1 1 0] Result: [[ 2 3 3] [ 5 6 6] [ 8 9 9] [11 12 12]]
Method 2: Using Loop (Manual Approach)
Manually iterate through each row and add the vector ?
import numpy as np
original_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
vector = np.array([1, 1, 0])
result = np.empty_like(original_array)
for i in range(len(original_array)):
result[i, :] = original_array[i, :] + vector
print("Result using loop:")
print(result)
Result using loop: [[ 2 3 3] [ 5 6 6] [ 8 9 9] [11 12 12]]
How Broadcasting Works
NumPy automatically handles the dimension alignment. The vector [1, 1, 0] is broadcast to match each row of the 4×3 array.
Comparison
| Method | Performance | Code Length | Best For |
|---|---|---|---|
| Broadcasting | Fast (vectorized) | 1 line | All cases |
| Manual Loop | Slower | 3+ lines | Learning purposes |
Conclusion
Use NumPy broadcasting (array + vector) for efficient vector addition to arrays. Broadcasting automatically handles dimension alignment and provides better performance than manual loops.
Advertisements
