1.

What do you understand by Vectorization in NumPy?

Answer»

Function Vectorization technically means that the function is applied to all elements in the array. Typically, certain python functionalities on arrays (such as loops) are slower in nature because python arrays can contain elements of different data types. Since the C program expects a specific datatype, there are chances of compiler optimisation which makes C code run faster. Since NumPy arrays support storing elements of a single datatype, most of the implementations of the functions written in NumPy meant for arithmetic, logical operations etc have optimised C program code under their hood. Additionally, NumPy also helps developers create their own vectorised functions by following the below steps:


  • Write your required function that takes array elements as parameters.

  • Vectorize the function by making use of the vectorize() method of the NumPy package.

  • Give array inputs to the vectorized function.

The below example demonstrates the process of vectorization.

import numpy as np
# Define your function
def add(arr1, arr2):
return (arr1 + arr2)

arr1 = np.array([1,2,3])
arr2 = np.array([4,5,6])

#vectorize add method
vectorized_add = np.vectorize(add)

#call vectorized method
result = vectorized_add(arr1, arr2)

print(result)

The output of above code

 [5 7 9]


Discussion

No Comment Found