Array Operations & Vectorization
One of the biggest strengths of NumPy is its ability to perform fast and efficient operations on entire arrays without writing loops.
This is achieved through array operations and vectorization.
Understanding these concepts is critical because :
- They make code faster
- They reduce complexity
- They are widely used in real-world data analytics and machine learning
What Are Array Operations?
Array operations allow you to perform mathematical and logical operations directly on NumPy arrays.
Instead of processing values one by one, NumPy processes the entire array at once.
Basic Arithmetic Operations
NumPy supports element-wise arithmetic operations.
Example :
import numpy as np
arr1 = np.array([10, 20, 30])
arr2 = np.array([1, 2, 3])
print(arr1 + arr2)
print(arr1 - arr2)
print(arr1 * arr2)
print(arr1 / arr2)
# Output:
[11 22 33]
[ 9 18 27]
[10 40 90]
[10. 10. 10.]
Each operation is applied element by element.
Operations with Scalars
You can also perform operations between an array and a scalar (a single number).
NumPy automatically applies the operation to each element in the array.
Example :
import numpy as np
arr = np.array([10, 20, 30])
print(arr + 5)
print(arr * 2)
print(arr - 10)
# Output:
[15 25 35]
[20 40 60]
[ 0 10 20]
This is very common in analytics tasks like :
- Applying tax
- Increasing prices
- Normalizing values
Real-Life Example: Price Increase
Imagine you have a list of product prices and you want to apply a 10% increase to all products.
import numpy as np
prices = np.array([100, 200, 300])
new_prices = prices * 1.1
print(new_prices)
# Output:
[110. 220. 330.]
What Is Vectorization?
Vectorization means performing operations on arrays without using explicit loops.
NumPy executes vectorized code at a much lower level (C language), which makes it extremely fast.
Vectorized vs Non-Vectorized Code
Using Python Loop (Not Recommended)
data = [1, 2, 3, 4, 5]
result = []
for x in data:
result.append(x * 2)
print(result)
# Output:
[2, 4, 6, 8, 10]
Using NumPy Vectorization (Recommended)
arr = np.array([1, 2, 3, 4, 5])
result = arr * 2
print(result)
# Output:
[ 2 4 6 8 10]
- Cleaner
- Faster
- Easier to read
Why Vectorization Is Faster
Vectorization is faster because :
- Operations are performed in compiled C code (not Python loops)
- Optimized low-level execution
- Better memory usage
This becomes very important for large datasets.
Mathematical Functions on Arrays
NumPy provides built-in mathematical functions that work on entire arrays.
Common Examples :
import numpy as np
arr = np.array([1, 4, 9, 16])
print(np.sqrt(arr)) # Square root
print(np.log(arr)) # Natural logarithm
print(np.exp(arr)) # Exponential
print(np.sum(arr)) # Sum of elements
print(np.mean(arr)) # Mean of elements
print(np.max(arr)) # Maximum element
print(np.min(arr)) # Minimum element
# Output:
[1. 2. 3. 4.]
[0. 1.38629436 2.19722458 2.77258872]
[2.71828183e+00 5.45981500e+01 8.10308393e+03 8.88611052e+06]
30
7.5
16
1
These functions are heavily used in analytics and statistics.
Statistical Operations (Real Analytics Use)
sales = np.array([1200, 1500, 1800, 1600, 2000])
print("Total Sales:", np.sum(sales))
print("Average Sales:", np.mean(sales))
print("Highest Sale:", np.max(sales))
print("Lowest Sale:", np.min(sales))
# Output:
Total Sales: 8100
Average Sales: 1620.0
Highest Sale: 2000
Lowest Sale: 1200
This kind of analysis is common in :
- Financial reporting
- Sales performance tracking
- Inventory management
- Dashboards
Comparison Operations
You can compare arrays with scalars or other arrays, which returns a boolean array.
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr > 25) # Greater than
print(arr == 20) # Equal to
print(arr <= 30) # Less than or equal to
# Output:
[False False True True]
[False False True False]
[ True True True False]
This returns a Boolean array, often used for filtering.
Combining Operations
Operations can be chained together.
arr = np.array([10, 20, 30, 40])
result = np.sqrt(arr) * 2
print(result)
# Output:
[6.32455532 8.94427191 10.95445115 12.64911064]
This allows powerful transformations in minimal code.
Operations on Multidimensional Arrays
NumPy supports operations on multidimensional arrays just like 1D arrays.
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(matrix * 2)
print(np.sum(matrix))
# Output:
[[ 2 4 6]
[ 8 10 12]]
Operations apply to all elements automatically.
Common Beginner Mistakes
- Using loops instead of vectorization
- Mixing incompatible shapes
- Forgetting that operations are element-wise
- Ignoring performance benefits
Understanding vectorization helps avoid these issues.
Why Array Operations & Vectorization Matter
They help :
- Improve performance
- Write cleaner code
- Handle large datasets efficiently
- Build scalable analytics solutions
Almost all data analytics and ML libraries expect vectorized data.
Key Takeaways
- Vectorization is faster than loops
- Operations are element-wise
- Mathematical functions work on entire arrays
- Boolean arrays are useful for filtering
- Multidimensional arrays support the same operations
Conclusion
Array operations and vectorization are fundamental to efficient data analysis in Python. They allow for:
- Fast computation on large datasets
- Clean, readable code
- Scalable solutions for analytics and machine learning