📌 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.