import numpy as np import matplotlib.pyplot as plt %matplotlib inline np.array([1, 2, 3]) np.array([1, 2, 3], dtype=np.float32) np.array([[1, 2, 3], [4, 5, 6]]) np.arange(5, 10) np.linspace(5, 10, 10) np.empty((3, 2)) np.zeros((3, 2)) np.ones((3, 2)) np.eye(3) np.diag([1, 2, 3]) np.repeat(3, 5) np.repeat([[1, 2, 3]], 3, axis=0) a = np.arange(3 * 4).reshape(3, -1) a.shape a.size a.dtype a.nbytes np.random.seed(0) np.random.rand(3, 4) np.random.randn(3, 4) plt.hist(np.random.normal(10, 2.0, 1000)); plt.hist(np.random.binomial(1, 0.8, 1000)); v = np.arange(3) v v.reshape(-1, 1) # column matrix v[:, np.newaxis] # column matrix v.reshape(1, -1) # row vector v[np.newaxis, :] # row vector r = v[np.newaxis, :] # returns view -> no copy r[0, 0] = 10 r v A = np.arange(3 * 4).reshape(3, -1) A A.flatten() A.flatten()[0] = 10 A A.ravel() A.ravel()[0] = 100 A A.ravel() a = np.arange(10) a[1] a[[0, 5]] a[-1] a[:5] a[5:] a[5::2] b = a[::2] b[2] = -1 b a a[a > 5] A = np.arange(3 * 4).reshape(3, 4) A A[1, :] b = A.take(1, axis=0) A.take(1, axis=1) b b[0] = 10 b A A = np.arange(1, 7).reshape(3,2) A A * 2 A + 2 v = np.array([1, 2]) v A.dot(v) v.dot(v) A.sum() A.sum(axis=0) A.sum(axis=1) A.prod(axis=0) A.mean(axis=0) A.std(axis=0) A.min(axis=0) A # Scaling rows r = np.array([[2, 3]]) A * r # Scaling columns c = np.array([1, 2, 3]).reshape(3, -1) A * c A (2d array): 5 x 4 B (1d array): 1 Result (2d array): 5 x 4 A (2d array): 5 x 4 B (1d array): 4 Result (2d array): 5 x 4 A (3d array): 15 x 3 x 5 B (3d array): 15 x 1 x 5 Result (3d array): 15 x 3 x 5 A (3d array): 15 x 3 x 5 B (2d array): 3 x 5 Result (3d array): 15 x 3 x 5 A (3d array): 15 x 3 x 5 B (2d array): 3 x 1 Result (3d array): 15 x 3 x 5 A = np.ones((2, 3, 5)) b = np.arange(3).reshape(3, 1) A b A + b Ac = np.ones((10, 100000), order='C') # C order Af = np.ones((10, 100000), order='F') # Fortran order %timeit Ac.sum(axis=0) %timeit Af.sum(axis=0) Ac = np.ones((100000, 10), order='C') Af = np.ones((100000, 10), order='F') %timeit Ac.sum(axis=1) %timeit Af.sum(axis=1)