np.array([[1.5, 2, 3], [4, 5, 6]], dtype=float)np.zeros([2, 2]) # 2x2 constant matrix filled with 0np.ones([2, 2]) # 2x2 constant matrix filled with 1np.full([2, 2], 7) # 2x2 constant matrix filled with 7np.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 matrixnp.random.rand(2, 2) # 2x2 uniform random matrixnp.random.randn(2, 2) # 2x2 normal random matrixnp.zeros_like(arr) # arr-like matrix filled with 3np.ones_like(arr) # arr-like matrix filled with 3np.full_like(arr, 3) # arr-like matrix filled with 3xv, 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 filenp.savez("array.npz", a=a_arr, b=b_arr, ...) # Save several arrays in uncompressed binary filenp.savez_compressed("array.npz", a=a_arr, b=b_arr, ...) # Save several arrays in compressed binary filenp.load("array.npy")# load CSV datanp.loadtxt('data.csv', dtype='object', delimiter=',', skiprows=1) # load a CSV file in an ndarray without its header.
A.view() # Share data, not the structureA.copy() # Deep copy
Sorting
A.sort(axis=1)
Slicing and Indexing
# SlicingA[0:2, 1] # Select items at rows 0 and 1 in column 1A[1, ...] # Same as [1, :, :]A[::-1] # Reversed array of A# IndexingA[A<2]# List indexingA[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)# Examplelist_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.TA.reshape([2, 6])np.append(A, a) # Append items to an arraynp.delete(A, 1, 0) # (array, object, axis)np.ravel() # return a view (references the same memory address)np.flatten() # return a copyA.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 solvingA = 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 findingeig_vals, eig_vecs = np.linalg.eig(A)