This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow and in the numpy documentation. I've also created some to reach the 100 limit. 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
(hint: import … as …)
(hint: np.__version__, np.show_config)
(hint: np.zeros)
(hint: size, itemsize)
(hint: np.info)
(hint: array[4])
(hint: np.arange)
(hint: array[::-1])
(hint: reshape)
(hint: np.nonzero)
(hint: np.eye)
(hint: np.random.random)
(hint: min, max)
(hint: mean)
(hint: array[1:-1, 1:-1])
(hint: np.pad)
(hint: NaN = not a number, inf = infinity)
0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
0.3 == 3 * 0.1
(hint: np.diag)
(hint: array[::2])
(hint: np.unravel_index)
(hint: np.tile)
(hint: (x - min) / (max - min))
(hint: np.dtype)
(hint: np.dot | @)
(hint: >, <=)
(hint: np.sum)
# Author: Jake VanderPlas
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z
np.array(0) / np.array(0)
np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float)
(hint: np.uniform, np.copysign, np.ceil, np.abs)
(hint: np.intersect1d)
(hint: np.seterr, np.errstate)
(hint: imaginary number)
np.sqrt(-1) == np.emath.sqrt(-1)
(hint: np.datetime64, np.timedelta64)
(hint: np.arange(dtype=datetime64['D']))
(hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=))
(hint: %, np.floor, np.ceil, astype, np.trunc)
(hint: np.arange)
(hint: np.fromiter)
(hint: np.linspace)
(hint: sort)
(hint: np.add.reduce)
(hint: np.allclose, np.array_equal)
(hint: flags.writeable)
44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
(hint: np.sqrt, np.arctan2)
(hint: argmax)
(hint: np.meshgrid)
(hint: np.iinfo, np.finfo, eps)
(hint: np.set_printoptions)
(hint: argmin)
(hint: dtype)
52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
(hint: np.atleast_2d, T, np.sqrt)
(hint: astype(copy=False))
(hint: np.genfromtxt)
1, 2, 3, 4, 5
6, , , 7, 8
, , 9,10,11
(hint: np.ndenumerate, np.ndindex)
(hint: np.meshgrid, np.exp)
(hint: np.put, np.random.choice)
(hint: mean(axis=,keepdims=))
(hint: argsort)
(hint: any, ~)
(hint: np.abs, argmin, flat)
62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)
(hint: np.nditer)
(hint: class method)
64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)
(hint: np.bincount | np.add.at)
(hint: np.bincount)
(hint: np.unique)
(hint: sum(axis=(-2,-1)))
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)
(hint: np.diag)
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])
71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
(hint: array[:, :, None])
(hint: array[[]] = array[[]])
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)
74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)
(hint: np.repeat)
(hint: np.cumsum)
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)
(hint: np.logical_not, np.negative)
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])? (★★★)
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])? (★★★)
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) (★★★)
(hint: minimum, maximum)
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)
(hint: np.linalg.svd)
(hint: np.bincount, argmax)
(hint: stride_tricks.as_strided)
(hint: class method)
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)
(hint: np.add.reduceat)
(hint: np.argsort | np.argpartition)
90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)
(hint: np.indices)
(hint: np.core.records.fromarrays)
(hint: np.power, *, np.einsum)
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)
(hint: np.unpackbits)
(hint: np.ascontiguousarray)
97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)
(hint: np.einsum)
98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?
(hint: np.cumsum, np.interp)
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)
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)