Selected Reading

NumPy - Vectorization with Arrays



Vectorization with Arrays in NumPy

Vectorization refers to the process of applying operations directly on entire arrays or vectors, rather than iterating through individual elements. In NumPy, we can achieve this by performing element-wise operations using highly optimized "C" and "Fortran" libraries.

Following are the advantages of using vectorization in NumPy −

  • Performance: Vectorized operations are much faster than similar operations implemented with loops in Python.
  • Readability: Code that uses vectorization is more concise and easier to understand.
  • Scalability: Vectorization allows you to work efficiently with large datasets.

Basic Vectorized Operations

As we know that vectorized operations in NumPy is used to perform element-wise operations on entire arrays without the need for explicit loops. Few common operations which can be applied directly to arrays includes −

  • Arithmetic Operations
  • Mathematical Functions
  • Comparison Operators

Element-wise Arithmetic Operations

Element-wise arithmetic operations in NumPy include addition, subtraction, multiplication, and division. These operations are performed directly on arrays, applying the arithmetic operation to each corresponding element.

For example, adding two arrays will result in a new array where each element is the sum of the corresponding elements in the original arrays.

Example

In the following example, each element of a is added to the corresponding element of b without the need for a loop −

import numpy as np

# Create two arrays
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

# Perform element-wise addition
result = a + b

print("Result of Addition:", result)

Following is the output obtained −

Result of Addition: [11 22 33 44]

Element-wise Mathematical Functions

NumPy provides a wide range of mathematical functions (such as exponential, logarithmic, and trigonometric functions) that perform element-wise operations on arrays.

These functions allow you to perform complex mathematical transformations on arrays by calling a single function.

Example

In this example, we are performing element-wise exponentiation using the np.exp() function. This calculates the exponential for each element in the array −

import numpy as np
# Create an array
a = np.array([1, 2, 3, 4])

# Perform element-wise exponentiation
result = np.exp(a)

print("Exponential of Array:", result)

This will produce the following result −

Exponential of Array: [ 2.71828183  7.3890561  20.08553692 54.59815003]

Comparison Operations

Element-wise comparison operations allow you to compare arrays directly, resulting in a boolean array indicating the result of the comparison for each element. These operations include comparisons like greater than, less than, and equality.

Example

Here, we perform an element-wise comparison to check if each element is greater than 2. This results in a Boolean array indicating True or False for each comparison −

import numpy as np
# Create an array
a = np.array([1, 2, 3, 4])

# Perform element-wise comparison
result = a > 2

print("Comparison Result:", result)

Following is the output of the above code −

Comparison Result: [False False  True  True]

Vectorizing Custom Functions

Vectorizing custom functions in NumPy allows you to apply a function to an entire array element-wise.

You can use np.vectorize() function to convert a standard Python function into a vectorized function, making it possible to handle arrays directly. This simplifies the code by eliminating the need for explicit loops.

Using np.vectorize() Function

If you have a custom function that operates on individual elements, you can use np.vectorize() function to apply this function to entire arrays in a vectorized manner.

Example

In the example below, we define a custom function to square a number and use the vectorize() function to apply this function element-wise to a NumPy array −

import numpy as np
# Define a custom function
def square(x):
   return x ** 2

# Vectorize the custom function
vectorized_square = np.vectorize(square)

# Create an array
a = np.array([1, 2, 3, 4])

# Apply the vectorized function
result = vectorized_square(a)

print("Squared Array:", result)

The output obtained is as shown below −

Squared Array: [ 1  4  9 16]

Limitations of vectorize() Function

While np.vectorize() function makes it easy to apply custom functions to arrays, it is essentially a convenience function and does not provide the same performance benefits as true vectorized operations does.

For optimal performance, it is better to use built-in NumPy functions or rewrite the function to take advantage of vectorization.

Vectorized Operations with Multi-dimensional Arrays

You can apply vectorized operations in NumPy directly to multi-dimensional arrays, helping to perform element-wise calculations across all dimensions without writing explicit loops.

Example

In the following example, we create two 2D arrays and perform matrix multiplication using the np.dot() function −

import numpy as np
# Create two 2D arrays (matrices)
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

# Perform matrix multiplication using vectorization
result = np.dot(a, b)

print("Matrix Multiplication Result:\n", result)

The result is a new matrix obtained by multiplying the two original matrices −

Matrix Multiplication Result:
[[19 22]
 [43 50]]
Advertisements