NumPy Cheat Sheet Standard arithmetic operations Broadcasting
EPFL CS 233
Introduction to Machine Learning Elementwise arithmetic operations Broadcasting enables operations that combine arrays of
(Version 1) Addition d = e + f
different shapes.
Array initialization Subtraction d = e - f
Multiplication d = e * f
Create arrays from (potentially nested) Python lists: Division d = e / f
Rank 1 a = [Link]([1, 2, 3])
Square root d = [Link](e)
Rank 2 b = [Link]([[1, 2, 3],
Exponentiation d = [Link](e)
[4, 5, 6]]) Natural logarithm d = [Link](e)
A two dimensional array multiplied by a one dimensional
Cosine d = [Link](e)
Force a datatype c = [Link]([0, 1, 2], array results in broadcasting if number of 1D array
dtype=np.int32) elements matches the number of 2D array columns.
Other functions
Functions to create standard arrays (e.g. all zeros):
Dot/Matrix product d = [Link](e, f)
Zero-filled array a = [Link]((2,2))
d = e @ f
One-filled array b = [Link]((1,2)) Compute sum of each column d = [Link](b, axis=0)
Random array d = [Link]((2,2)) Compute max value of each row d = [Link](b, axis=1)
Identity matrix c = [Link](2) Compute min value of array d = [Link](b)
Increasing sequence e = [Link](2.0, 8.0, 10) Transpose matrix d = e.T
Note that the first three functions require a shape tuple Note that * and @ are different. The former does element-
argument, hence the double parentheses. wise multiplication, while the latter is a dot or matrix- Broadcasting can stretch both arrays to form an output
matrix/vector product depending on the input shapes. array larger than either of the initial arrays.
Data Types
Basic data types:
Inspecting arrays
Unsigned 32 bit integer np.uint32
Signed 64 bit integer np.int64
Basic definitions:
Single precision floating point np.float32
Double precision floating point np.float64 Array dimensions [Link]
Boolean [Link] Number of array dimensions [Link]
Number of array elements [Link]
Number of array elements in a row [Link][0]
Array indexing, slicing
Data type of array elements [Link]
Basic indexing notation: Cast an array to a different type [Link](np.float32)
Select the element at the 3rd index a[3]
Select the element at row 2, column 0 b[2][0] Reshaping, Copying
Slicing:
Select elements at index 0 and 1 a[0:2] Reshape an array d = [Link](6, 1)
Select all elements in column 1 b[:,1:2] Extend the dimensionality # shape (2, 3)
Select first two rows and last two columns b[:2,-2:] a = [Link]([[1, 2, 3],
[4, 5, 6]])
Indexing using a list of indices: # shape (2, 1, 3)
a[:, None, :]
Select elements (1,1) and (2,1) b[[1,2],[1,1]]
Flatten array to 1D [Link]()
[Link]((-1, ))
Indexing using masking: Create a deep copy of b c = [Link](b)
Select elements less than 4 b[b<4]
Cheat-sheet by S. Arpa and J. Bednarik ([[Link]|[Link]]@[Link]).
LATEX template by Michelle Cristina de Sousa Baltazar.