0
0
NumPydata~5 mins

Vectorization over loops in NumPy

Choose your learning style9 modes available
Introduction

Vectorization makes your code faster and simpler by doing many calculations at once instead of one by one.

When you want to add two lists of numbers quickly.
When you need to multiply all elements in a big array without writing a loop.
When you want to apply a math operation to every item in a dataset.
When you want to avoid slow loops in data processing.
When working with large data arrays and want faster results.
Syntax
NumPy
result = array1 + array2
result = np.sin(array)
result = array * 2

Vectorized operations work element-wise on arrays.

You do not need to write explicit loops for these operations.

Examples
Adds two arrays element by element without a loop.
NumPy
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
sum_arr = arr1 + arr2
print(sum_arr)
Calculates sine of each element in the array at once.
NumPy
import numpy as np

arr = np.array([0, np.pi/2, np.pi])
sin_arr = np.sin(arr)
print(sin_arr)
Multiplies every element by 2 without a loop.
NumPy
import numpy as np

arr = np.array([1, 2, 3, 4])
doubled = arr * 2
print(doubled)
Sample Program

This program shows how to add, multiply, and apply sine to arrays using vectorized operations. It avoids loops and runs faster.

NumPy
import numpy as np

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

# Vectorized addition
sum_arr = arr1 + arr2

# Vectorized multiplication
product_arr = arr1 * arr2

# Vectorized sine calculation
angles = np.array([0, np.pi/2, np.pi])
sin_values = np.sin(angles)

print("Sum:", sum_arr)
print("Product:", product_arr)
print("Sine values:", sin_values)
OutputSuccess
Important Notes

Vectorized code is usually much faster than loops in Python.

Make sure arrays have the same shape or compatible shapes for operations.

Use numpy functions for math operations to get vectorization benefits.

Summary

Vectorization lets you do many calculations at once on arrays.

It makes code simpler and faster by avoiding explicit loops.

Use numpy arrays and functions to apply vectorization in data science.