1. Basics
Importing NumPy
import numpy as np
Creating Arrays
arr = np.array([1, 2, 3]) matrix = np.array([[1, 2], [3, 4]])
Array Attributes
arr.shape # (3,) arr.ndim # 1 arr.size # 3 arr.dtype # dtype('int64')
Array Initialization
zeros = np.zeros((2, 3)) # 2x3 matrix of zeros ones = np.ones((3, 3)) # 3x3 matrix of ones identity = np.eye(3) # 3x3 Identity matrix random = np.random.rand(2, 2) # 2x2 matrix of random floats between 0 and 1
2. Array Indexing and Slicing
Indexing
arr[0] # 1st element matrix[1, 0] # 2nd row, 1st column element
Slicing
arr[1:] # [2, 3] matrix[:, 1] # 2nd column matrix[1, :] # 2nd row
Boolean Indexing/ Masking
arr[arr > 1] # [2, 3] (elements greater than 1)
3. Array Operations
Element-wise Operations
arr + 5 # Add 5 to each element arr * 2 # Multiply each element by 2
Matrix Multiplication
matrix1 = [[1, 2], [2, 3]] matrix2 = [[4, 5], [6, 7]] np.dot(matrix1, matrix2) # Matrix product #So, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7] #So the computed answer will be: [[16, 26], [19, 31]]
Broadcasting
arr = np.array([1, 2, 3]) arr + np.array([1]) # Broadcast to [1, 1, 1]
Aggregate Functions
np.sum(arr) # Sum of all elements np.mean(arr) # Mean np.min(arr) # Minimum element np.argmax(arr) # Index of the max element
4. Reshaping and Transposing
Reshaping
reshaped = arr.reshape((3, 1)) # Convert 1D to 2D (3 rows, 1 column)
Transposing
matrix.T # Transpose of the matrix
5. Advanced Indexing
- Fancy Indexing
pythonCopy codearr = np.array([10, 20, 30, 40])
index = [0, 2]
arr[index] # [10, 30]
- Condition-based Indexing
pythonCopy codearr[arr > 15] # [20, 30, 40]
6. Stacking and Splitting
- Vertical and Horizontal Stacking
pythonCopy codea = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.vstack((a, b)) # Stack vertically
np.hstack((a, b)) # Stack horizontally
- Splitting Arrays
pythonCopy codesplit_arr = np.split(arr, 2) # Split array into 2 parts
7. Advanced Broadcasting
- Broadcasting rules
pythonCopy codea = np.array([[1], [2], [3]])
b = np.array([4, 5, 6])
a + b # Broadcast across dimensions
8. Linear Algebra
- Determinant and Inverse
pythonCopy codenp.linalg.det(matrix) # Determinant
np.linalg.inv(matrix) # Inverse of the matrix
- Eigenvalues and Eigenvectors
pythonCopy codeeigvals, eigvecs = np.linalg.eig(matrix) # Eigenvalues and eigenvectors
9. Random Sampling
- Random Numbers
pythonCopy coderand_arr = np.random.rand(3, 3) # Random floats
rand_int = np.random.randint(1, 10, (3, 3)) # Random integers
- Shuffling
pythonCopy codenp.random.shuffle(arr) # Shuffle array in-place
- Set Random Seed
pythonCopy codenp.random.seed(42) # Set seed for reproducibility
10. Statistical Operations
- Basic Statistics
pythonCopy codenp.mean(arr) # Mean
np.median(arr) # Median
np.std(arr) # Standard deviation
- Histogram
pythonCopy codehist, bin_edges = np.histogram(arr, bins=5)
11. Saving and Loading
- Saving Arrays
pythonCopy codenp.save('array.npy', arr) # Save as .npy file
np.savetxt('array.txt', arr, delimiter=',') # Save as .txt
- Loading Arrays
pythonCopy codearr = np.load('array.npy')
arr = np.loadtxt('array.txt', delimiter=',')
12. Broadcasting Rules
NumPy allows broadcasting of arrays for element-wise operations, provided:
- Dimensions are compatible (either equal or one is 1).
- The smaller array is stretched without copying data.
13. Advanced ufunc (Universal Functions)
- Custom ufunc
pythonCopy codedef custom_function(x):
return x * 2
ufunc = np.frompyfunc(custom_function, 1, 1)
ufunc(np.array([1, 2, 3])) # Apply custom ufunc
This cheatsheet covers essential NumPy functionalities, from basic array manipulations to advanced topics like linear algebra and broadcasting.