This is a collection of exercises that have been collected in the numpy mailing list, on stack
overflow
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
and new
users but also to provide a set of exercises for those who teach.
If you find an error or think you’ve a better way to
solve some of them, feel
free to open an issue at https://github.com/rougier/numpy-100.
File automatically generated. See the documentation to update questions/answers/hints programmatically.
¶1. Import the numpy package under the name np (★☆☆)
hint: import … as
1
import numpy as np
¶2. Print the numpy version and the configuration (★☆☆)
Z = np.zeros(10) Z.flags.writeable = False Z[0] = 1
¶44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
hint: np.sqrt, np.arctan2
1 2 3 4 5 6
Z = np.random.random((10,2)) X,Y = Z[:,0], Z[:,1] R = np.sqrt(X**2+Y**2) T = np.arctan2(Y,X) print(R) print(T)
¶45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)
hint: argmax
1 2 3
Z = np.random.random(10) Z[Z.argmax()] = 0 print(Z)
¶46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)
hint: np.meshgrid
1 2 3 4
Z = np.zeros((5,5), [('x',float),('y',float)]) Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5), np.linspace(0,1,5)) print(Z)
¶47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)
hint: np.subtract.outer
1 2 3 4 5 6
# Author: Evgeni Burovski
X = np.arange(8) Y = X + 0.5 C = 1.0 / np.subtract.outer(X, Y) print(np.linalg.det(C))
¶48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
hint: np.iinfo, np.finfo, eps
1 2 3 4 5 6 7
for dtype in [np.int8, np.int32, np.int64]: print(np.iinfo(dtype).min) print(np.iinfo(dtype).max) for dtype in [np.float32, np.float64]: print(np.finfo(dtype).min) print(np.finfo(dtype).max) print(np.finfo(dtype).eps)
¶49. How to print all the values of an array? (★★☆)
hint: np.set_printoptions
1 2 3
np.set_printoptions(threshold=float("inf")) Z = np.zeros((40,40)) print(Z)
¶50. How to find the closest value (to a given scalar) in a vector? (★★☆)
hint: argmin
1 2 3 4
Z = np.arange(100) v = np.random.uniform(0,100) index = (np.abs(Z-v)).argmin() print(Z[index])
¶51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)
w, h = 256, 256 I = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte) colors = np.unique(I.reshape(-1, 3), axis=0) n = len(colors) print(n)
# Faster version # Author: Mark Setchell # https://stackoverflow.com/a/59671950/2836621
w, h = 256, 256 I = np.random.randint(0,4,(h,w,3), dtype=np.uint8)
# View each pixel as a single 24-bit integer, rather than three 8-bit bytes I24 = np.dot(I.astype(np.uint32),[1,256,65536])
# Count unique colours n = len(np.unique(I24)) print(n)
¶67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)
hint: sum(axis=(-2,-1))
1 2 3 4 5 6 7 8
A = np.random.randint(0,10,(3,4,3,4)) # solution by passing a tuple of axes (introduced in numpy 1.7.0) sum = A.sum(axis=(-2,-1)) print(sum) # solution by flattening the last two dimensions into one # (useful for functions that don't accept tuples for axis argument) sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1) print(sum)
¶68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★)
hint: np.bincount
1 2 3 4 5 6 7 8 9 10 11 12
# Author: Jaime Fernández del Río
D = np.random.uniform(0,1,100) S = np.random.randint(0,10,100) D_sums = np.bincount(S, weights=D) D_counts = np.bincount(S) D_means = D_sums / D_counts print(D_means)
# Pandas solution as a reference due to more intuitive code import pandas as pd print(pd.Series(D).groupby(S).mean())
¶69. How to get the diagonal of a dot product? (★★★)
hint: np.diag
1 2 3 4 5 6 7 8 9 10 11 12 13
# Author: Mathieu Blondel
A = np.random.uniform(0,1,(5,5)) B = np.random.uniform(0,1,(5,5))
# Slow version np.diag(np.dot(A, B))
# Fast version np.sum(A * B.T, axis=1)
# Faster version np.einsum("ij,ji->i", A, B)
¶70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)
hint: array[::4]
1 2 3 4 5 6 7
# Author: Warren Weckesser
Z = np.array([1,2,3,4,5]) nz = 3 Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz)) Z0[::nz+1] = Z print(Z0)
¶71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
hint: array[:, :, None]
1 2 3
A = np.ones((5,5,3)) B = 2*np.ones((5,5)) print(A * B[:,:,None])
A = np.arange(25).reshape(5,5) A[[0,1]] = A[[1,0]] print(A)
¶73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)
hint: repeat, np.roll, np.sort, view, np.unique
1 2 3 4 5 6 7 8 9
# Author: Nicolas P. Rougier
faces = np.random.randint(0,100,(10,3)) F = np.roll(faces.repeat(2,axis=1),-1,axis=1) F = F.reshape(len(F)*3,2) F = np.sort(F,axis=1) G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] ) G = np.unique(G) print(G)
¶74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)
hint: np.repeat
1 2 3 4 5
# Author: Jaime Fernández del Río
C = np.bincount([1,1,2,3,4,4,6]) A = np.repeat(np.arange(len(C)), C) print(A)
¶75. How to compute averages using a sliding window over an array? (★★★)
hint: np.cumsum, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Author: Jaime Fernández del Río
defmoving_average(a, n=3) : ret = np.cumsum(a, dtype=float) ret[n:] = ret[n:] - ret[:-n] return ret[n - 1:] / n Z = np.arange(20) print(moving_average(Z, n=3))
# Author: Jeff Luo (@Jeff1999) # make sure your NumPy >= 1.20.0
from numpy.lib.stride_tricks import sliding_window_view
Z = np.arange(20) print(sliding_window_view(Z, window_shape=3).mean(axis=-1))
¶76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (★★★)
hint: from numpy.lib import stride_tricks, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Author: Joe Kington / Erik Rigtorp from numpy.lib import stride_tricks
Z = np.arange(10) print(sliding_window_view(Z, window_shape=3))
¶77. How to negate a boolean, or to change the sign of a float inplace? (★★★)
hint: np.logical_not, np.negative
1 2 3 4 5 6 7
# Author: Nathaniel J. Smith
Z = np.random.randint(0,2,100) np.logical_not(Z, out=Z)
Z = np.random.uniform(-1.0,1.0,100) np.negative(Z, out=Z)
¶78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (★★★)
No hints provided...
1 2 3 4 5 6 7 8 9 10 11 12
defdistance(P0, P1, p): T = P1 - P0 L = (T**2).sum(axis=1) U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L U = U.reshape(len(U),1) D = P0 + U*T - p return np.sqrt((D**2).sum(axis=1))
¶79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)
No hints provided...
1 2 3 4 5 6 7
# Author: Italmassov Kuanysh
# based on distance function from previous question P0 = np.random.uniform(-10, 10, (10,2)) P1 = np.random.uniform(-10,10,(10,2)) p = np.random.uniform(-10, 10, (10,2)) print(np.array([distance(P0,P1,p_i) for p_i in p]))
¶80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a fill value when necessary) (★★★)
r = [slice(start,stop) for start,stop inzip(R_start,R_stop)] z = [slice(start,stop) for start,stop inzip(Z_start,Z_stop)] R[r] = Z[z] print(Z) print(R)
¶81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], …, [11,12,13,14]]? (★★★)
hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)
1 2 3 4 5 6 7 8 9 10
# Author: Stefan van der Walt
Z = np.arange(1,15,dtype=np.uint32) R = stride_tricks.as_strided(Z,(11,4),(4,4)) print(R)
# Author: Jeff Luo (@Jeff1999)
Z = np.arange(1, 15, dtype=np.uint32) print(sliding_window_view(Z, window_shape=4))
S = symetric(np.random.randint(0,10,(5,5))) S[2,3] = 42 print(S)
¶86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (★★★)
hint: np.tensordot
1 2 3 4 5 6 7 8 9 10 11 12 13
# Author: Stefan van der Walt
p, n = 10, 20 M = np.ones((p,n,n)) V = np.ones((p,n,1)) S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) print(S)
# It works, because: # M is (p,n,n) # V is (p,n,1) # Thus, summing over the paired axes 0 and 0 (of M and V independently), # and 2 and 1, to remain with a (n,1) vector.
¶87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)
hint: np.add.reduceat, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)
¶93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (★★★)
hint: np.where
1 2 3 4 5 6 7 8
# Author: Gabe Schwartz
A = np.random.randint(0,5,(8,3)) B = np.random.randint(0,5,(2,2))
C = (A[..., np.newaxis, np.newaxis] == B) rows = np.where(C.any((3,1)).all(1))[0] print(rows)
¶94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)
No hints provided...
1 2 3 4 5 6 7 8 9 10 11
# Author: Robert Kern
Z = np.random.randint(0,5,(10,3)) print(Z) # solution for arrays of all dtypes (including string arrays and record arrays) E = np.all(Z[:,1:] == Z[:,:-1], axis=1) U = Z[~E] print(U) # soluiton for numerical arrays only, will work for any number of columns in Z U = Z[Z.max(axis=1) != Z.min(axis=1),:] print(U)
¶95. Convert a vector of ints into a matrix binary representation (★★★)
hint: np.unpackbits
1 2 3 4 5 6 7 8 9 10
# Author: Warren Weckesser
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128]) B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int) print(B[:,::-1])
¶99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (★★★)
hint: np.logical_and.reduce, np.mod
1 2 3 4 5 6 7 8 9
# Author: Evgeni Burovski
X = np.asarray([[1.0, 0.0, 3.0, 8.0], [2.0, 0.0, 1.0, 1.0], [1.5, 2.5, 1.0, 0.0]]) n = 4 M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1) M &= (X.sum(axis=-1) == n) print(X[M])
¶100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (★★★)
hint: np.percentile
1 2 3 4 5 6 7 8
# Author: Jessica B. Hamrick
X = np.random.randn(100) # random 1D array N = 1000# number of bootstrap samples idx = np.random.randint(0, X.size, (N, X.size)) means = X[idx].mean(axis=1) confint = np.percentile(means, [2.5, 97.5]) print(confint)