ADVERTISEMENT
ADVERTISEMENT

How to use NumPy Vectorize?

Vectorization in NumPy means operating on arrays rather than individual elements. This is one of NumPy's main advantages for numerical computations.

Python's element-by-element operations can be slow, especially for huge data sets. This is vectorization. Instead of operating on each element, you can operate on the entire array.

This has two main advantages:

  1. Simplicity: You write operations between arrays much like you would write operations between scalar values. The code is often more concise and easier to read.

  2. Performance: Due to the nature of the NumPy library and the programming language it's built on (C), performing operations on entire arrays is often much faster than performing operations on individual elements using loops.

An example follows. You wish to add numbers from two arrays:

Without vectorization (using a loop):

import numpy as np

a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 10])

result = np.empty(5)
for i in range(5):
    result[i] = a[i] + b[i]

With vectorization:

The np.vectorize function in numpy is used to vectorize a function that typically receives a scalar input so that it can be applied to all elements of an array. Here's an example:

Suppose you have a function calculate that takes a number and performs some operation. Let's say it checks if the number is even or odd:

def calculate(x):
    return "even" if x % 2 == 0 else "odd"

That's where np.vectorize comes in:

import numpy as np

def calculate(x):
    return "even" if x % 2 == 0 else "odd"

vcalculate = np.vectorize(calculate) # Vectorizing the function

arr = np.array([1, 2, 3, 4, 5])

result = vcalculate(arr) # Now you can use it with an array

print(result) 
# Outputs: array(['odd', 'even', 'odd', 'even', 'odd'], dtype='<U4')
In this code, np.vectorize(calculate) returns a new function that applies the calculate function to every element of an array. When you call vcalculate(arr), it applies the calculate function to every element of arr and returns a new array containing the results.

 


ADVERTISEMENT

ADVERTISEMENT