The document provides an extensive cheatsheet on NumPy, covering topics like array creation, inspection, indexing/slicing, mathematics, manipulation, broadcasting, linear algebra, random functions, saving/loading, advanced operations, structured arrays, datetimes, polynomials, I/O, error handling, and more. It lists numerous NumPy functions and methods, describing what each does through short code examples. The cheatsheet acts as a reference for working with NumPy and its multi-dimensional array and matrix capabilities.
The document provides an extensive cheatsheet on NumPy, covering topics like array creation, inspection, indexing/slicing, mathematics, manipulation, broadcasting, linear algebra, random functions, saving/loading, advanced operations, structured arrays, datetimes, polynomials, I/O, error handling, and more. It lists numerous NumPy functions and methods, describing what each does through short code examples. The cheatsheet acts as a reference for working with NumPy and its multi-dimensional array and matrix capabilities.
● Determinant of a matrix: det = np.linalg.det(matrix) ● Inverse of a matrix: inv = np.linalg.inv(matrix) ● Eigenvalues and eigenvectors: eigenvalues, eigenvectors = np.linalg.eig(matrix) ● Solve linear equations Ax = b: x = np.linalg.solve(matrix, np.array([1, 2])) ● Dot product of two arrays: dot_product = np.dot(arr1, arr2) ● Matrix multiplication: mat_product = np.matmul(matrix1, matrix2) ● Inverse of a matrix: inv_matrix = np.linalg.inv(matrix) ● Determinant of a matrix: det = np.linalg.det(matrix) ● Solve linear matrix equation: x = np.linalg.solve(A, b) ● Eigenvalues and eigenvectors: eigenvalues, eigenvectors = np.linalg.eig(matrix) ● Singular Value Decomposition: U, s, V = np.linalg.svd(matrix) ● Cross product of two vectors: cross_prod = np.cross(vec1, vec2) ● Norm of a vector or matrix: norm = np.linalg.norm(vec_or_matrix) ● Rank of a matrix: rank = np.linalg.matrix_rank(matrix) ● Trace of a matrix: trace = np.trace(matrix)
9. Random Functions
● Set random seed: np.random.seed(0)
● Random permutation of elements: np.random.shuffle(arr) ● Randomly select elements: choice = np.random.choice(arr)
10. Saving and Loading
By: Waleed Mousa
● Save array to file: np.save('my_array', arr) ● Load array from file: loaded_arr = np.load('my_array.npy') ● Save multiple arrays to a zip file: np.savez('array_archive.npz', arr1=arr, arr2=arr2) ● Load arrays from a zip file: loaded_data = np.load('array_archive.npz')
11. Advanced Operations
● Element-wise maximum of two arrays: max_elements = np.maximum(arr,
another_arr) ● Element-wise minimum: min_elements = np.minimum(arr, another_arr) ● Find unique elements: unique_elements = np.unique(arr) ● Count occurrences of each value: value_counts = np.bincount(arr) ● Clip array values within an interval: clipped_arr = np.clip(arr, a_min=1, a_max=2) ● Round elements to the nearest integer: rounded_arr = np.rint(arr) ● Find non-zero elements: non_zero_indices = np.nonzero(arr) ● Replace nan with zero: no_nan_arr = np.nan_to_num(arr) ● Check if elements are finite: is_finite = np.isfinite(arr) ● Check for NaN: is_nan = np.isnan(arr) ● Element-wise comparison: comparison = np.equal(arr1, arr2) ● Logarithm base 10: log10_arr = np.log10(arr) ● Logarithm base 2: log2_arr = np.log2(arr) ● Sine function: sin_arr = np.sin(arr) ● Cosine function: cos_arr = np.cos(arr) ● Tangent function: tan_arr = np.tan(arr) ● Arcsine, arccosine, arctangent: asin_arr, acos_arr, atan_arr = np.arcsin(arr), np.arccos(arr), np.arctan(arr) ● Hyperbolic sine, cosine, tangent: sinh_arr, cosh_arr, tanh_arr = np.sinh(arr), np.cosh(arr), np.tanh(arr) ● Inverse hyperbolic sine, cosine, tangent: asinh_arr, acosh_arr, atanh_arr = np.arcsinh(arr), np.arccosh(arr), np.arctanh(arr) ● Degrees to radians and vice versa: radians = np.radians(arr); degrees = np.degrees(radians) ● Histogram: hist, bin_edges = np.histogram(arr, bins=10)
● Save array as text: np.savetxt('file.txt', arr) ● Load CSV: csv_data = np.genfromtxt('file.csv', delimiter=',') ● Save array as CSV: np.savetxt('file.csv', arr, delimiter=',')
16. Error Handling
● Suppress warnings: np.seterr(all='ignore')
● Catch warnings as errors: np.seterr(all='raise')
17. Miscellaneous
● Generate a meshgrid: X, Y = np.meshgrid(x_range, y_range)
● Find the grid points of a Cartesian product: grid = np.indices((3, 3)) ● Repeat elements of an array: repeated_arr = np.repeat(arr, 3)
By: Waleed Mousa
● Tile an array: tiled_arr = np.tile(arr, (2, 3)) ● Find the cumulative product: cumprod_arr = np.cumprod(arr) ● Create a diagonal matrix: diag_matrix = np.diag(arr) ● Create a 2D array with a diagonal: diag2d = np.diagflat([1, 2, 3]) ● Kronecker product of two arrays: kronecker = np.kron(arr1, arr2) ● Create a sparse matrix: sparse_matrix = np.eye(5, k=1) - np.eye(5, k=-1) ● Compute the convolution of two arrays: convolution = np.convolve(a, v, mode='full') ● Evaluate a function over a grid: eval_grid = np.vectorize(my_func)(X, Y) ● Find indices where condition is true: true_indices = np.where(condition)
18. Financial Functions
● Future value of an investment: future_value = np.fv(rate=0.05,
nper=10, pmt=-100, pv=-1000) ● Present value of future cash flows: present_value = np.pv(rate=0.05, nper=10, pmt=0, fv=1000) ● Net present value of an investment: npv = np.npv(rate=0.05, values=[-1000, 100, 200, 300, 400, 500]) ● Payment against loan principal plus interest: payment = np.pmt(rate=0.05, nper=10, pv=1000) ● Interest payment for a loan: interest_payment = np.ipmt(rate=0.05, per=1, nper=10, pv=1000) ● Principal payment for a loan: principal_payment = np.ppmt(rate=0.05, per=1, nper=10, pv=1000) ● Number of periods for an investment: num_periods = np.nper(rate=0.05, pmt=-150, pv=1000) ● Rate of interest per period: interest_rate = np.rate(nper=10, pmt=-100, pv=1000, fv=0)
20. Random Sampling
● Generate random numbers from a uniform distribution:
uniform_randoms = np.random.rand(10)
By: Waleed Mousa
● Normal distribution random numbers: normal_randoms = np.random.randn(10) ● Random integers within a range: random_integers = np.random.randint(low=1, high=100, size=10) ● Shuffle an array in-place: np.random.shuffle(arr) ● Generate a random sample from a given 1-D array: sample = np.random.choice(arr, size=3) ● Set seed for reproducibility: np.random.seed(42)
● Bitwise OR: bitwise_or = np.bitwise_or(arr1, arr2) ● Bitwise XOR: bitwise_xor = np.bitwise_xor(arr1, arr2) ● Bitwise NOT: bitwise_not = np.bitwise_not(arr) ● Left shift elements of an array: left_shift = np.left_shift(arr, 2) ● Right shift elements of an array: right_shift = np.right_shift(arr, 2)
22. Set Operations
● Intersection of two arrays: intersect = np.intersect1d(arr1, arr2)
● Union of two arrays: union = np.union1d(arr1, arr2) ● Set difference: difference = np.setdiff1d(arr1, arr2) ● Set symmetric difference: sym_diff = np.setxor1d(arr1, arr2) ● Test whether each element of an array is also present in a second array: in1d = np.in1d(arr1, arr2)
23. Sorting, Searching, and Counting
● Sort an array: sorted_arr = np.sort(arr)
● Argsort (indices that would sort an array): indices = np.argsort(arr) ● Lexsort (indirect stable sort on multiple keys): indices = np.lexsort((key1, key2)) ● Searchsorted (find indices where elements should be inserted to maintain order): indices = np.searchsorted(sorted_arr, values)
By: Waleed Mousa
● Partition (partial sort): partitioned_arr = np.partition(arr, 3) ● Argpartition (indices that would partition an array): indices = np.argpartition(arr, 3) ● Count non-zero values: count_nonzero = np.count_nonzero(arr) ● Find maximum and minimum values and their indices: max_val, min_val = np.max(arr), np.min(arr); max_idx, min_idx = np.argmax(arr), np.argmin(arr)
Python Advanced Programming: The Guide to Learn Python Programming. Reference with Exercises and Samples About Dynamical Programming, Multithreading, Multiprocessing, Debugging, Testing and More
Python Advanced Programming: The Guide to Learn Python Programming. Reference with Exercises and Samples About Dynamical Programming, Multithreading, Multiprocessing, Debugging, Testing and More