π Introduction
One of the biggest advantages of using NumPy is its ability to perform fast mathematical operations on arrays.
Unlike Python lists, NumPy allows vectorized computations, making calculations extremely efficient.
π’ Basic Arithmetic Operations
NumPy allows element-wise operations.
import numpy as npa = np.array([1, 2, 3])
b = np.array([4, 5, 6])print(a + b)
print(a - b)
print(a * b)
print(a / b)
π Output:
[5 7 9]
[-3 -3 -3]
[ 4 10 18]
[0.25 0.4 0.5 ]
β‘ Scalar Operations
You can perform operations with a single number.
a = np.array([1, 2, 3])print(a * 2)
π Output:
[2 4 6]
π Power & Square Root
import numpy as npa = np.array([1, 4, 9])print(np.sqrt(a))
print(np.power(a, 2))
π Output:
[1. 2. 3.]
[ 1 16 81]
π Logarithmic & Exponential Functions
a = np.array([1, 2, 3])print(np.log(a))
print(np.exp(a))
π Trigonometric Functions
a = np.array([0, np.pi/2, np.pi])print(np.sin(a))
print(np.cos(a))
π¦ Aggregation Operations
a = np.array([10, 20, 30])print(np.sum(a))
print(np.min(a))
print(np.max(a))
π Output:
60
10
30
β‘ Why NumPy is Fast?
NumPy uses:
- Vectorization (no loops)
- Optimized C backend
- Parallel computation
π Real-World Example
prices = np.array([100, 200, 300])discount = prices * 0.9
print(discount)
π Output:
[ 90. 180. 270.]
β Useful in:
- Finance
- Data analysis
- Machine learning
π Works with Other Libraries
Used in:
- Pandas
- TensorFlow
- Scikit-learn
π Summary Table
| Operation | Function |
|---|---|
| Addition | a + b |
| Multiplication | a * b |
| Square root | np.sqrt() |
| Log | np.log() |
| Sum | np.sum() |
π§ Pro Tips
- Use vectorized operations instead of loops
- Combine multiple operations for efficiency
- Use NumPy functions for better performance
π Conclusion
Mathematical operations in NumPy are fast, efficient, and essential for modern data processing.