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

Algorithm

Step 1: Define a numpy array.
Step 2: Define a vector.
Step 3: Create a result array same as the original array.
Step 4: Add vector to each row of the original array.
Step 5: Print the result array.

Example Code

import numpy as np

original_array = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print("Original Array: \n", original_array)

vector = np.array([1,1,0])
print("\nVector: ", vector)
result = np.empty_like(original_array)
for i in range(4):
   result[i,:] = original_array[i,:] + vector
print("\nResult: \n", result)

Output

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]]

Explanation

The statement result = np.empty_like(original_array) creates a empty array 'result' of the same dimensions as the original_array

Updated on: 16-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements