NumPy — Notes
1. Introduction
• NumPy (Numerical Python) is a core Python library for scientific computing.
• Provides support for large, multi-dimensional arrays and matrices.
• Offers mathematical functions, linear algebra, random number generation, and more.
2. NumPy Arrays
• ndarray: Core object representing homogeneous multidimensional data.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
Array creation methods
np.zeros((2,3)) # 2x3 matrix of zeros
np.ones((2,2)) # 2x2 matrix of ones
np.arange(0,10,2) # [0,2,4,6,8]
np.linspace(0,1,5) # 5 values between 0 and 1
np.eye(3) # 3x3 Identity matrix
3. Array Attributes
arr = np.arange(12).reshape(3,4)
arr.shape # (3, 4)
arr.ndim # 2
arr.size # 12
arr.dtype # int64
arr.itemsize # bytes per element
1
4. Indexing & Slicing
arr = np.array([10,20,30,40,50])
arr[0] # 10
arr[1:4] # [20 30 40]
mat = np.array([[1,2,3],[4,5,6]])
mat[0,1] # 2
mat[:,1] # column → [2 5]
5. Array Operations
• Vectorized arithmetic (faster than loops)
a = np.array([1,2,3])
b = np.array([4,5,6])
print(a + b) # [5 7 9]
print(a * 2) # [2 4 6]
• Universal functions (ufuncs)
np.sqrt(a) # [1.0, 1.41, 1.73]
np.exp(b)
np.sin(a)
6. Linear Algebra
A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])
np.dot(A,B) # matrix multiplication
np.linalg.inv(A) # inverse
np.linalg.eig(A) # eigenvalues & vectors
2
7. Random Module
np.random.rand(3) # uniform [0,1)
np.random.randn(3) # normal distribution
np.random.randint(1,10,5) # 5 ints between 1-9
8. Broadcasting
• Different shapes are combined automatically when compatible.
A = np.ones((3,3))
B = np.array([1,2,3])
print(A + B) # row-wise broadcast
9. File I/O
np.savetxt("data.csv", arr, delimiter=",")
arr2 = np.loadtxt("data.csv", delimiter=",")
10. Use Cases
• Data preprocessing in ML/AI
• Efficient numerical computations
• Used with Pandas, SciPy, scikit-learn, TensorFlow, PyTorch
Conclusion
NumPy is the foundation of Python’s data science ecosystem, enabling fast mathematical operations and
serving as the base for higher-level libraries.