NumPy Detailed Notes
Introduction to NumPy
• NumPy (Numerical Python): A Python library used for numerical computations, arrays, linear
algebra, Fourier transform, statistics, etc.
• Why NumPy? Faster than Python lists, supports multidimensional arrays, vectorized operations,
and provides mathematical functions.
• Import:
import numpy as np
Creating Arrays
• From lists: np.array([1,2,3])
• Zeros/Ones: np.zeros((2,3)), np.ones((3,3))
• Identity: np.eye(4)
• Full: np.full((2,2),7)
• Range: np.arange(0,10,2), np.linspace(0,1,5)
• Random: np.random.rand(3,2), np.random.randint(1,10,5)
Array Attributes
• ndim → Dimensions
• shape → Rows & Columns
• size → Total elements
• dtype → Data type
• itemsize → Bytes per element
Indexing & Slicing
• a[0], a[-1], a[1:4]
• 2D: arr[0,1], arr[:,1], arr[1,:]
• Subarray: arr[0:2,1:3]
Array Operations
• Arithmetic: +, -, *, /, **
• Universal Functions: np.sqrt, np.exp, np.log, np.sin, np.max, np.sum, np.mean
• Broadcasting: arr + scalar or different shapes
Reshaping & Flattening
• arr.reshape(3,4), arr.reshape(-1,6)
• Flatten: arr.ravel() (view), arr.flatten() (copy)
Stacking & Splitting
• Stacking: np.hstack, np.vstack, np.concatenate
• Splitting: np.hsplit, np.vsplit
Copy vs View
• y = x → Reference
• z = x.copy() → Independent
Sorting & Searching
• np.sort(arr), np.argsort(arr)
• np.where(arr>1), np.nonzero(arr), np.unique(arr)
Linear Algebra
• np.dot(a,b) or a @ b
• np.transpose(a)
• np.linalg.inv(a), np.linalg.det(a), np.linalg.eig(a)
File I/O
• Save: np.save('data.npy', a)
• Load: np.load('data.npy')
• Text: np.savetxt('file.txt', a), np.loadtxt('file.txt')
Advanced
• Masked arrays, Vectorization, Random seed
• Fancy Indexing: a[[0,2,4]] → select indices