NumPy OperationsΒΆ
NumPyβs true power comes from its ability to perform fast, element-wise operations on entire arrays without writing explicit loops. Operations fall into two categories: array-with-array arithmetic (where corresponding elements are combined) and scalar-with-array arithmetic (where a single value is applied to every element). Both leverage vectorized C code under the hood, delivering performance that pure Python cannot match.
ArithmeticΒΆ
You can easily perform array with array arithmetic, or scalar with array arithmetic. Letβs see some examples:
import numpy as np
arr = np.arange(0,11)
arr
arr + arr
arr * arr
arr - arr
Scalar Operations (Broadcasting)ΒΆ
When you apply an arithmetic operator between an array and a single number (a scalar), NumPy broadcasts the scalar across every element. For example, arr + 100 adds 100 to each element. This broadcasting mechanism eliminates the need for loops and is the same principle that powers feature scaling ((X - mean) / std) and bias addition in neural network layers.
arr + 100
Division Edge CasesΒΆ
NumPy handles division edge cases gracefully. Dividing zero by zero produces nan (not a number), and dividing a non-zero number by zero produces inf (infinity). Both emit warnings but do not raise exceptions, so your code continues to run. In data science, nan values are common in real-world datasets and must be handled explicitly using functions like np.isnan() or np.nan_to_num() before feeding data into models.
# Warning on division by zero, but not an error!
# Just replaced with nan
arr/arr
# Also warning, but not an error instead infinity
1/arr
arr**3
Universal Array FunctionsΒΆ
Numpy comes with many universal array functions, which are essentially just mathematical operations you can use to perform the operation across the array. Letβs show some common ones:
#Taking Square Roots
np.sqrt(arr)
#Calcualting exponential (e^)
np.exp(arr)
np.max(arr) #same as arr.max()
np.sin(arr)
np.log(arr)
Great Job!ΒΆ
Thatβs all we need to know for now!