Basic Operations in NumPy
NumPy is designed for fast and efficient numerical computation. One of its biggest strengths is how easily it performs mathematical operations on entire arrays.
In this lesson, you will learn how NumPy handles basic arithmetic operations such as addition, subtraction, multiplication, division, and comparisons.
Element-wise Arithmetic Operations
NumPy applies arithmetic operations element by element when working with arrays of the same shape.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([2, 4, 6])
print(a + b)
print(a - b)
print(a * b)
print(a / b)
Output:
[12 24 36]
[ 8 16 24]
[ 20 80 180]
[5. 5. 5.]
Each operation is performed between corresponding elements of both arrays.
Operations Between Array and Scalar
You can also perform operations between an array and a single value (scalar).
arr = np.array([5, 10, 15, 20])
print(arr + 5)
print(arr * 2)
Output:
[10 15 20 25]
[10 20 30 40]
NumPy automatically applies the operation to every element.
Comparison Operations
Comparison operators return boolean arrays, which are useful for filtering data.
scores = np.array([45, 72, 88, 60, 30])
print(scores > 60)
print(scores == 60)
Output:
[False True True False False]
[False False False True False]
These boolean results are commonly used with Boolean Indexing.
Combining Arithmetic and Boolean Operations
You can combine arithmetic and comparison logic in a single workflow.
marks = np.array([35, 50, 75, 90])
adjusted = marks + 5
passed = adjusted >= 40
print(adjusted)
print(passed)
Output:
[40 55 80 95]
[ True True True True]
This approach is very common in grading systems and data transformations.
Mathematical Functions
NumPy provides built-in mathematical functions that work efficiently on arrays.
values = np.array([1, 4, 9, 16])
print(np.sqrt(values))
print(np.sum(values))
print(np.mean(values))
Output:
[1. 2. 3. 4.]
30
7.5
These functions are heavily used in statistics, analytics, and machine learning.
Real-World Example
Consider daily sales figures and calculate a 10% increase.
sales = np.array([1200, 1500, 1800, 2000])
updated_sales = sales * 1.10
print(updated_sales)
Output:
[1320. 1650. 1980. 2200.]
NumPy makes bulk calculations simple and readable.
Practice Exercise
Exercise
Create a NumPy array of 5 numbers and:
- Add 10 to each element
- Multiply each element by 3
- Check which values are greater than 50
Expected Outcome
You should confidently perform arithmetic and comparison operations on arrays.
What’s Next?
In the next lesson, you will learn about Vectorized Computation and why NumPy operations are much faster than traditional Python loops.