Introduction
Vectorization helps your code run faster by doing many calculations at once instead of one by one.
Jump into concepts and practice - no test required
Vectorization helps your code run faster by doing many calculations at once instead of one by one.
import numpy as np # Vectorized operation example result = np.array1 + np.array2
import numpy as np # Adding two arrays element-wise arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) sum_arr = arr1 + arr2 print(sum_arr)
import numpy as np # Using vectorized sine function angles = np.array([0, np.pi/2, np.pi]) sines = np.sin(angles) print(sines)
import numpy as np # Slow loop version arr = np.array([1, 2, 3, 4]) squares = [] for x in arr: squares.append(x**2) print(squares) # Fast vectorized version squares_vec = arr**2 print(squares_vec)
This program compares adding two large arrays element-wise using a slow Python loop versus a fast vectorized operation with NumPy. It prints the time taken by each method and confirms the results match.
import numpy as np import time # Create large arrays size = 1000000 arr1 = np.random.rand(size) arr2 = np.random.rand(size) # Slow loop addition def slow_add(a, b): result = [] for i in range(len(a)): result.append(a[i] + b[i]) return result start = time.time() slow_result = slow_add(arr1, arr2) end = time.time() print(f"Slow loop time: {end - start:.4f} seconds") # Fast vectorized addition start = time.time() fast_result = arr1 + arr2 end = time.time() print(f"Vectorized time: {end - start:.4f} seconds") # Check results are close print(f"Results close: {np.allclose(slow_result, fast_result)}")
Vectorized code uses optimized C code inside NumPy and SciPy for speed.
Avoid Python loops on large arrays when possible for better performance.
Use functions like np.add, np.multiply, np.sin, np.exp for vectorized math.
Vectorization makes math on arrays faster and simpler.
Use NumPy and SciPy functions that work on whole arrays.
Avoid explicit loops for big data calculations.
a and b element-wise using vectorization?c = a + b.for i in range(len(a)): c[i] = a[i] + b[i] uses a loop (not vectorized), np.add(a, b, out=None, where=False) has wrong parameters, c = a.append(b) is invalid for arrays.+ for vectorized array addition [OK]c = a + b for fast element-wise addition [OK]import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) z = np.dot(x, y)
import numpy as np arr = np.array([1, 2, 3]) result = arr * 2 print(result[3])
data. You want to compute the mean of each column efficiently. Which approach is best?np.mean(data, axis=0) to compute means vectorized -> Option D