Introduction
When you work with data in NumPy, it's often not about manipulating a single value—it's about performing calculations across entire arrays. Whether you're adding a constant, subtracting arrays element-wise, or calculating percentages, NumPy's arithmetic operations make it simple and fast.
Why Use NumPy for Arithmetic?
Standard Python lists require looping for element-wise calculations, which is inefficient. NumPy arrays are optimized for vectorized operations—this means you can write cleaner code that runs significantly faster.
Basic Arithmetic Operations
Let’s explore the foundational arithmetic operations in NumPy. These include:
- Addition
- Subtraction
- Multiplication
- Division
- Modulus (remainder)
- Exponentiation (power)
Step-by-Step Examples
1. Setup: Import NumPy
import numpy as np
2. Create Sample Arrays
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
These two arrays have the same shape and can be used for element-wise operations.
3. Addition
result = a + b
print(result)
Output: [11 22 33]
Each element of a
is added to the corresponding element in b
.
4. Subtraction
result = a - b
print(result)
Output: [ 9 18 27]
Works element by element, just like basic algebra.
5. Multiplication
result = a * b
print(result)
Output: [10 40 90]
Performs element-wise multiplication, not matrix multiplication.
6. Division
result = a / b
print(result)
Output: [10. 10. 10.]
Division always returns a float array, even if all numbers are integers.
7. Modulus (Remainder)
result = a % b
print(result)
Output: [0 0 0]
Shows the remainder of division element-wise. All elements divide evenly here.
8. Exponentiation
result = a ** b
print(result)
Output: [ 10 400 27000]
Raises each element of a
to the power of the corresponding element in b
.
Broadcasting: Arithmetic with Scalars
result = a + 5
print(result)
Output: [15 25 35]
NumPy automatically broadcasts the scalar (5) across the entire array.
Precautions and Tips
- Always ensure arrays are compatible in shape before element-wise operations. Mismatched shapes raise a
ValueError
. - Division by zero returns
inf
ornan
, not a crash—NumPy is designed for numerical robustness. - Use
np.seterr()
to configure how floating-point errors are handled (e.g., ignore, warn, or raise).
Verification Tips
- Check
array.shape
before performing operations. - Use
np.allclose()
to compare arrays with floating-point values. - Always print and validate results during learning or debugging.
Conclusion
Arithmetic operations in NumPy are intuitive and incredibly powerful. By mastering these basics, you unlock the true performance of numerical Python. Whether you're building machine learning models, analyzing data, or just crunching numbers, these operations form the foundation of every NumPy workflow.
Next Steps
In the next topic, we'll dive deeper into Broadcasting—one of NumPy’s most powerful features that lets you operate on arrays of different shapes. Stay tuned!