0% found this document useful (0 votes)
44 views

(Numpy) - Extended Cheatsheet

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.

Uploaded by

Valdano SODE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

(Numpy) - Extended Cheatsheet

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.

Uploaded by

Valdano SODE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

# [ Numpy ] [ Extended cheatsheet ]

1. Importing NumPy

● Import NumPy: import numpy as np

2. Array Creation

● Create a 1D array: arr = np.array([1, 2, 3])


● Create a 2D array (matrix): matrix = np.array([[1, 2], [3, 4]])
● Create an array of zeros: zeros = np.zeros((2, 3))
● Create an array of ones: ones = np.ones((3, 3))
● Create a constant array: const = np.full((2, 2), 7)
● Create an identity matrix: I = np.eye(3)
● Create an array of evenly spaced values: range_arr = np.arange(0,
10, 2)
● Create a linearly spaced array: lin_arr = np.linspace(0, 1, 5)
● Create a random array: rand_arr = np.random.rand(2, 3)
● Create a random integer array: rand_int_arr = np.random.randint(0,
10, (2, 3))
● Create an empty array (uninitialized memory): empty_arr =
np.empty((3, 2))
● Copy an array: arr_copy = np.copy(arr)

3. Array Inspection

● Print array type: print(arr.dtype)


● Print array shape: print(arr.shape)
● Change array shape (without changing data): reshaped =
arr.reshape(1, -1)
● Print array size (total number of elements): print(arr.size)
● Print array dimension: print(arr.ndim)

4. Indexing and Slicing

● Access array elements: elem = arr[0]


● Access 2D array elements: elem2d = matrix[0, 1]

By: Waleed Mousa


● Slice a portion of the array: slice_arr = arr[1:3]
● Slice a 2D array (submatrix): submatrix = matrix[0:2, 1:2]
● Conditional indexing: cond_arr = arr[arr > 1]

5. Array Mathematics

● Addition: arr_sum = np.add(arr, 1)


● Subtraction: arr_sub = np.subtract(arr, 1)
● Multiplication (element-wise): arr_mul = np.multiply(arr, 2)
● Division: arr_div = np.divide(arr, 2)
● Square root: arr_sqrt = np.sqrt(arr)
● Dot product: dot_product = np.dot(arr, arr)
● Cross product: cross_product = np.cross(arr, arr)
● Exponential: arr_exp = np.exp(arr)
● Logarithm: arr_log = np.log(arr)
● Absolute value: arr_abs = np.abs(arr)
● Power: arr_pow = np.power(arr, 2)
● Sum of elements: arr_sum = np.sum(arr)
● Cumulative sum: arr_cumsum = np.cumsum(arr)
● Mean: arr_mean = np.mean(arr)
● Median: arr_median = np.median(arr)
● Standard deviation: arr_std = np.std(arr)
● Variance: arr_var = np.var(arr)
● Minimum and maximum: arr_min, arr_max = np.min(arr), np.max(arr)
● Argmin and Argmax (indices of min and max): idx_min, idx_max =
np.argmin(arr), np.argmax(arr)
● Normalize an array: arr_normalized = (arr - np.mean(arr)) /
np.std(arr)

6. Array Manipulation

● Flatten array: flat_arr = arr.flatten()


● Transpose array/matrix: transposed = matrix.T
● Concatenate arrays: concat_arr = np.concatenate((arr, arr))
● Stack arrays vertically: vert_stack = np.vstack((arr, arr))
● Stack arrays horizontally: horiz_stack = np.hstack((arr, arr))
● Split array: split_arr = np.split(arr, 2)
By: Waleed Mousa
● Vertical split: vert_split = np.vsplit(matrix, 2)
● Horizontal split: horiz_split = np.hsplit(matrix, 2)

7. Broadcasting and Vectorization

● Broadcasting example: broadcasted_sum = arr + np.array([1, 2, 3])


● Vectorized operations: vec_op = arr + 2

8. Linear Algebra

● Matrix multiplication: mat_mul = np.matmul(matrix, matrix)


● 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)

By: Waleed Mousa


12. Structured Arrays

● Access structured array by column name: names =


structured_arr['name']

13. Datetime Operations

● Create datetime array: dates = np.array(['2021-03-04',


'2024-04-05'], dtype='datetime64')
● Find the difference between dates: date_diff = np.diff(dates)

14. Polynomials

● Define a polynomial: p = np.poly1d([3, 2, -1]) # 3x^2 + 2x - 1


● Evaluate a polynomial: val = p(0)
● Find polynomial roots: roots = p.roots
● Polynomial addition, subtraction, multiplication, division: p_sum
= np.polyadd(p1, p2); p_sub = np.polysub(p1, p2); p_mul =
np.polymul(p1, p2); p_div = np.polydiv(p1, p2)

15. I/O with NumPy

● Load text: data = np.loadtxt('file.txt')


● 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)

21. Bitwise Operations

● Bitwise AND: bitwise_and = np.bitwise_and(arr1, arr2)


● 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)

By: Waleed Mousa

You might also like