Creating Arrays

np.array([[1.5, 2, 3], [4, 5, 6]], dtype=float)
 
np.zeros([2, 2]) # 2x2 constant matrix filled with 0
np.ones([2, 2]) # 2x2 constant matrix filled with 1
np.full([2, 2], 7) # 2x2 constant matrix filled with 7
 
np.arange(10, 25, 5) # ndarray version of range (start, end, step)
np.linspace(0, 2, 9) # 1d Array of evenly spaced values (start, end, num)
np.eye(2) # 2x2 identity matrix
np.random.rand(2, 2) # 2x2 uniform random matrix
np.random.randn(2, 2) # 2x2 normal random matrix
 
np.zeros_like(arr) # arr-like matrix filled with 3
np.ones_like(arr) # arr-like matrix filled with 3
np.full_like(arr, 3) # arr-like matrix filled with 3
 
xv, yv = np.meshgrid(x, y) # Both x and y are vectors
# xv.shape == yv.shape == (len(y), len(x))

I/O

np.save("array.npy", a_arr) # Save an array to a binary file
np.savez("array.npz", a=a_arr, b=b_arr, ...) # Save several arrays in uncompressed binary file
np.savez_compressed("array.npz", a=a_arr, b=b_arr, ...) # Save several arrays in compressed binary file
 
np.load("array.npy")
 
# load CSV data
np.loadtxt('data.csv', dtype='object', delimiter=',', skiprows=1) # load a CSV file in an ndarray without its header.

Data Types

Data typeValue/Range
np.boolTrue, False
np.int8, np.byte-128 ~ 127
np.uint8, np.ubyte0 ~ 255
np.int16, np.short-32768 ~ 32767
np.uint16, np.ushort0 ~ 65535
np.int32, np.intc-2147483648 ~ 2147483647
np.uint32, np.uintc0 ~ 4294967295
np.int64, np.long-9223372036854775808 ~ 9223372036854775807
np.uint64, np.ulong0 ~ 18446744073709551615
np.float16, np.halfsign bit, 5 bits exponent, 10 bits mantissa
np.float32, np.singlesign bit, 8 bits exponent, 23 bits mantissa
np.float64, np.doublesign bit, 11 bits exponent, 52 bits mantissa
np.complex64, np.csingletwo 32-bit floats (real and imaginary components)
np.complex128, np.cdoubletwo 64-bit floats (real and imaginary components)

Array Operations

Arithmetic Operations

A + B
np.add(A, B)
 
A - B
np.subtract(A, B)
 
A / B
np.divide(A, B)
 
A * B
np.multiply(A, B)
 
A @ B
np.matmul(A, B)
 
np.abs(A)
np.sqrt(A)
np.exp(A)
np.log(A)
np.log2(A)
np.log10(A)
np.round(A, decimal=2)
np.floor(A)
np.ceil(A)
np.sin(A)
np.cos(A)

Comparison

A == B # Element-wise comparison (The shape of the matrix is preserved)
A < 2
 
np.array_equal(A, B) # Array-wise comparison

Aggregate Functions

A.sum()
A.min()
A.max()
A.median()
 
A.cumsum()
>>> np.array([[1, 2, 3], [4, 5, 6]]).cumsum()
array([ 1,  3,  6, 10, 15, 21])
>>> np.array([[1, 2, 3], [4, 5, 6]]).cumsum(axis=0)
array([[1, 2, 3], [5, 7, 9]])
>>> np.array([[1, 2, 3], [4, 5, 6]]).cumsum(axis=1)
array([[1, 3, 6], [4, 9, 15]])
 
A.mean()

Copying Arrays

A.view() # Share data, not the structure
A.copy() # Deep copy

Sorting

A.sort(axis=1)

Slicing and Indexing

# Slicing
A[0:2, 1] # Select items at rows 0 and 1 in column 1
A[1, ...] # Same as [1, :, :]
A[::-1] # Reversed array of A
 
# Indexing
A[A<2]
# List indexing
A[d0_list, d1_list, d2_list] # Use zip([d0_list, d1_list, d2_list]) as an index, result is an vector.

Searching

# Find indices where elements should be inserted to maintain order.
np.searchsorted(list_a, list_b)
 
# Example
list_a := np.arange(0, 10.5, 0.5) # [0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6., 6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10.]
list_b := np.array([3, 5, 7, 2])
np.searchsorted(list_a, list_b) # [6, 10, 14, 4]

Array Manipulation

np.transpose(A)
A.T
 
A.reshape([2, 6])
np.append(A, a) # Append items to an array
np.delete(A, 1, 0) # (array, object, axis)
 
np.ravel() # return a view (references the same memory address)
np.flatten() # return a copy
A.squeeze()
 
np.concatenate([A, B], axis=0)
np.vstack([A, B])
np.hstack([A, B])

Calculus

dydx = np.gradient(y, x) # where both x, y are ndarrays

Linear Algebra

# systems of equations solving
A = np.array([[3, 2, 1], [5, -5, 4], [6, 0, 1]])
C = np.array([4, 3, 0])
np.linalg.solve(A, C)
  
## Eigenvalues and vectors finding
eig_vals, eig_vecs = np.linalg.eig(A)

Applications

Discrete Inverse Transform Sampling

lmbda = 1  
f = np.vectorize(lambda x: lmbda*np.exp(-lmbda*x))  
F = np.vectorize(lambda x: 1 - np.exp(-lmbda*x))  
  
x_range = np.linspace(0, 10, 1000)  
# Discrete inverse transform Sampling  
U = np.random.rand(1000)  
samples = x_range[np.searchsorted(F(x_range)[:-1], U)]  
  
_, ax = plt.subplots(figsize=(4, 2))  
ax.plot(x_range, f(x_range), label='$f(x)$')  
ax.plot(x_range, F(x_range), label='$F(x)$')  
ax.hist(samples, bins=30, density=True, label='samples')  
ax.legend(loc='center right', borderaxespad=1)  
plt.show()