Introduction
Vectorized operations let us do math on whole lists of numbers at once. This makes our code faster and easier to read.
Vectorized operations let us do math on whole lists of numbers at once. This makes our code faster and easier to read.
result = array1 + array2
result = array * 2
result = np.sin(array)Operations apply to each element automatically.
No need for explicit loops like for to process each item.
import numpy as np arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) sum_arr = arr1 + arr2 print(sum_arr)
import numpy as np arr = np.array([1, 2, 3]) double_arr = arr * 2 print(double_arr)
import numpy as np arr = np.array([0, np.pi/2, np.pi]) sin_arr = np.sin(arr) print(sin_arr)
This program adds two big arrays using vectorized addition. It is very fast and simple.
import numpy as np # Create two large arrays arr1 = np.arange(1_000_000) arr2 = np.arange(1_000_000, 2_000_000) # Vectorized addition result = arr1 + arr2 # Show first 5 results print(result[:5])
Vectorized code runs much faster than loops in Python.
It uses optimized C code inside numpy for speed.
Always try vectorized operations when working with arrays.
Vectorized operations apply math to whole arrays at once.
They make code simpler and much faster.
Use numpy vectorized operations for big data calculations.
a and b using vectorized operations?a + b and np.add(a, b) perform element-wise addition efficiently.import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) z = x * y print(z)
import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5]) z = x + y print(z)
Pass the test and this pattern moves unknown