Why NumPy exists, how it works, its functions, and real-world usage
NumPy (Numerical Python) is a core Python library used for fast mathematical and numerical computations.
Almost every data science, machine learning, AI, and scientific library in Python is built on top of NumPy.
Normal Python lists are slow for mathematical operations.
```data = [1, 2, 3, 4]
```
result = []
for x in data:
result.append(x * 2)
```
import numpy as np
```
data = np.array([1, 2, 3, 4])
result = data * 2
```
Before using NumPy functions, it is important to understand how a matrix (2D array) can be summed manually using nested loops.
Summing elements of an array or matrix is a very common operation in data processing. Let’s compare how this is done using traditional Python loops versus NumPy’s optimized functions.
This approach manually iterates through each element and adds it to a variable.
# Matrix (2D list)
matrix = [
[1, 2, 3],
[4, 5, 6]
]
total_sum = 0
# Loop through rows
for row in matrix:
# Loop through elements in each row
for value in row:
total_sum += value
print(total_sum) # Output: 21
total_sum
❌ Slower for large datasets
❌ More lines of code
NumPy performs summation internally using optimized C code, making it much faster.
import numpy as np
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(np.sum(matrix)) # Sum of all elements
print(np.sum(matrix, axis=0)) # Column-wise sum
print(np.sum(matrix, axis=1)) # Row-wise sum
The heart of NumPy is the ndarray (N-dimensional array).
import numpy as np
```
arr = np.array([1, 2, 3, 4])
```
Unlike Python lists, NumPy arrays:
np.array()
```
np.zeros((3,3))
np.ones((2,2))
np.arange(0, 10)
np.linspace(0, 1, 5)
```
arr.shape
```
arr.size
arr.dtype
arr.ndim
```
np.sum(arr)
```
np.mean(arr)
np.max(arr)
np.min(arr)
np.sqrt(arr)
```
np.dot(a, b)
```
np.transpose(a)
np.linalg.inv(matrix)
ML models are just mathematical formulas. NumPy is used to:
# Simple model calculation
```
prediction = np.dot(X, weights) + bias