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 (★☆☆)

  1. import numpy as np

2. Print the numpy version and the configuration (★☆☆)

  1. print(np.__version__)
  2. np.show_config()

3. Create a null vector of size 10 (★☆☆)

  1. Z = np.zeros(10)
  2. print(Z)

4. How to find the memory size of any array (★☆☆)

  1. Z = np.zeros((10,10))
  2. print("%d bytes" % (Z.size * Z.itemsize))

5. How to get the documentation of the numpy add function from the command line? (★☆☆)

  1. %run `python -c "import numpy; numpy.info(numpy.add)"`

6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)

  1. Z = np.zeros(10)
  2. Z[4] = 1
  3. print(Z)

7. Create a vector with values ranging from 10 to 49 (★☆☆)

  1. Z = np.arange(10,50)
  2. print(Z)

8. Reverse a vector (first element becomes last) (★☆☆)

  1. Z = np.arange(50)
  2. Z = Z[::-1]
  3. print(Z)

9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)

  1. Z = np.arange(9).reshape(3, 3)
  2. print(Z)

10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)

  1. nz = np.nonzero([1,2,0,0,4,0])
  2. print(nz)

11. Create a 3x3 identity matrix (★☆☆)

  1. Z = np.eye(3)
  2. print(Z)

12. Create a 3x3x3 array with random values (★☆☆)

  1. Z = np.random.random((3,3,3))
  2. print(Z)

13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)

  1. Z = np.random.random((10,10))
  2. Zmin, Zmax = Z.min(), Z.max()
  3. print(Zmin, Zmax)

14. Create a random vector of size 30 and find the mean value (★☆☆)

  1. Z = np.random.random(30)
  2. m = Z.mean()
  3. print(m)

15. Create a 2d array with 1 on the border and 0 inside (★☆☆)

  1. Z = np.ones((10,10))
  2. Z[1:-1,1:-1] = 0
  3. print(Z)

16. How to add a border (filled with 0’s) around an existing array? (★☆☆)

  1. Z = np.ones((5,5))
  2. Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
  3. print(Z)
  4. # Using fancy indexing
  5. Z[:, [0, -1]] = 0
  6. Z[[0, -1], :] = 0
  7. print(Z)

17. What is the result of the following expression? (★☆☆)

  1. 0 * np.nan
  2. np.nan == np.nan
  3. np.inf > np.nan
  4. np.nan - np.nan
  5. np.nan in set([np.nan])
  6. 0.3 == 3 * 0.1
  1. print(0 * np.nan)
  2. print(np.nan == np.nan)
  3. print(np.inf > np.nan)
  4. print(np.nan - np.nan)
  5. print(np.nan in set([np.nan]))
  6. print(0.3 == 3 * 0.1)

18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)

  1. Z = np.diag(1+np.arange(4),k=-1)
  2. print(Z)

19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)

  1. Z = np.zeros((8,8),dtype=int)
  2. Z[1::2,::2] = 1
  3. Z[::2,1::2] = 1
  4. print(Z)

20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)

  1. print(np.unravel_index(99,(6,7,8)))

21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)

  1. Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
  2. print(Z)

22. Normalize a 5x5 random matrix (★☆☆)

  1. Z = np.random.random((5,5))
  2. Z = (Z - np.mean (Z)) / (np.std (Z))
  3. print(Z)

23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)

  1. color = np.dtype([("r", np.ubyte),
  2. ("g", np.ubyte),
  3. ("b", np.ubyte),
  4. ("a", np.ubyte)])

24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)

  1. Z = np.dot(np.ones((5,3)), np.ones((3,2)))
  2. print(Z)
  3. # Alternative solution, in Python 3.5 and above
  4. Z = np.ones((5,3)) @ np.ones((3,2))
  5. print(Z)

25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)

  1. # Author: Evgeni Burovski
  2. Z = np.arange(11)
  3. Z[(3 < Z) & (Z < 8)] *= -1
  4. print(Z)

26. What is the output of the following script? (★☆☆)

  1. # Author: Jake VanderPlas
  2. print(sum(range(5),-1))
  3. from numpy import *
  4. print(sum(range(5),-1))
  1. # Author: Jake VanderPlas
  2. print(sum(range(5),-1))
  3. from numpy import *
  4. print(sum(range(5),-1))

27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)

  1. Z**Z
  2. 2 << Z >> 2
  3. Z <- Z
  4. 1j*Z
  5. Z/1/1
  6. Z<Z>Z
  1. Z**Z
  2. 2 << Z >> 2
  3. Z <- Z
  4. 1j*Z
  5. Z/1/1
  6. Z<Z>Z

28. What are the result of the following expressions? (★☆☆)

  1. np.array(0) / np.array(0)
  2. np.array(0) // np.array(0)
  3. np.array([np.nan]).astype(int).astype(float)
  1. print(np.array(0) / np.array(0))
  2. print(np.array(0) // np.array(0))
  3. print(np.array([np.nan]).astype(int).astype(float))

29. How to round away from zero a float array ? (★☆☆)

  1. # Author: Charles R Harris
  2. Z = np.random.uniform(-10,+10,10)
  3. print(np.copysign(np.ceil(np.abs(Z)), Z))
  4. # More readable but less efficient
  5. print(np.where(Z>0, np.ceil(Z), np.floor(Z)))

30. How to find common values between two arrays? (★☆☆)

  1. Z1 = np.random.randint(0,10,10)
  2. Z2 = np.random.randint(0,10,10)
  3. print(np.intersect1d(Z1,Z2))

31. How to ignore all numpy warnings (not recommended)? (★☆☆)

  1. # Suicide mode on
  2. defaults = np.seterr(all="ignore")
  3. Z = np.ones(1) / 0
  4. # Back to sanity
  5. _ = np.seterr(**defaults)
  6. # Equivalently with a context manager
  7. with np.errstate(all="ignore"):
  8. np.arange(3) / 0

32. Is the following expressions true? (★☆☆)

  1. np.sqrt(-1) == np.emath.sqrt(-1)
  1. np.sqrt(-1) == np.emath.sqrt(-1)

33. How to get the dates of yesterday, today and tomorrow? (★☆☆)

  1. yesterday = np.datetime64('today') - np.timedelta64(1)
  2. today = np.datetime64('today')
  3. tomorrow = np.datetime64('today') + np.timedelta64(1)

34. How to get all the dates corresponding to the month of July 2016? (★★☆)

  1. Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
  2. print(Z)

35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)

  1. A = np.ones(3)*1
  2. B = np.ones(3)*2
  3. np.add(A,B,out=B)
  4. np.divide(A,2,out=A)
  5. np.negative(A,out=A)
  6. np.multiply(A,B,out=A)

36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)

  1. Z = np.random.uniform(0,10,10)
  2. print(Z - Z%1)
  3. print(Z // 1)
  4. print(np.floor(Z))
  5. print(Z.astype(int))
  6. print(np.trunc(Z))

37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)

  1. Z = np.zeros((5,5))
  2. Z += np.arange(5)
  3. print(Z)
  4. # without broadcasting
  5. Z = np.tile(np.arange(0, 5), (5,1))
  6. print(Z)

38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)

  1. def generate():
  2. for x in range(10):
  3. yield x
  4. Z = np.fromiter(generate(),dtype=float,count=-1)
  5. print(Z)

39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)

  1. Z = np.linspace(0,1,11,endpoint=False)[1:]
  2. print(Z)

40. Create a random vector of size 10 and sort it (★★☆)

  1. Z = np.random.random(10)
  2. Z.sort()
  3. print(Z)

41. How to sum a small array faster than np.sum? (★★☆)

  1. # Author: Evgeni Burovski
  2. Z = np.arange(10)
  3. np.add.reduce(Z)

42. Consider two random array A and B, check if they are equal (★★☆)

  1. A = np.random.randint(0,2,5)
  2. B = np.random.randint(0,2,5)
  3. # Assuming identical shape of the arrays and a tolerance for the comparison of values
  4. equal = np.allclose(A,B)
  5. print(equal)
  6. # Checking both the shape and the element values, no tolerance (values have to be exactly equal)
  7. equal = np.array_equal(A,B)
  8. print(equal)

43. Make an array immutable (read-only) (★★☆)

  1. Z = np.zeros(10)
  2. Z.flags.writeable = False
  3. Z[0] = 1

44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)

  1. Z = np.random.random((10,2))
  2. X,Y = Z[:,0], Z[:,1]
  3. R = np.sqrt(X**2+Y**2)
  4. T = np.arctan2(Y,X)
  5. print(R)
  6. print(T)

45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)

  1. Z = np.random.random(10)
  2. Z[Z.argmax()] = 0
  3. print(Z)

46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)

  1. Z = np.zeros((5,5), [('x',float),('y',float)])
  2. Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
  3. np.linspace(0,1,5))
  4. print(Z)

47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)

  1. # Author: Evgeni Burovski
  2. X = np.arange(8)
  3. Y = X + 0.5
  4. C = 1.0 / np.subtract.outer(X, Y)
  5. print(np.linalg.det(C))

48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)

  1. for dtype in [np.int8, np.int32, np.int64]:
  2. print(np.iinfo(dtype).min)
  3. print(np.iinfo(dtype).max)
  4. for dtype in [np.float32, np.float64]:
  5. print(np.finfo(dtype).min)
  6. print(np.finfo(dtype).max)
  7. print(np.finfo(dtype).eps)

49. How to print all the values of an array? (★★☆)

  1. np.set_printoptions(threshold=float("inf"))
  2. Z = np.zeros((40,40))
  3. print(Z)

50. How to find the closest value (to a given scalar) in a vector? (★★☆)

  1. Z = np.arange(100)
  2. v = np.random.uniform(0,100)
  3. index = (np.abs(Z-v)).argmin()
  4. print(Z[index])

51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)

  1. Z = np.zeros(10, [ ('position', [ ('x', float, 1),
  2. ('y', float, 1)]),
  3. ('color', [ ('r', float, 1),
  4. ('g', float, 1),
  5. ('b', float, 1)])])
  6. print(Z)

52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)

  1. Z = np.random.random((10,2))
  2. X,Y = np.atleast_2d(Z[:,0], Z[:,1])
  3. D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
  4. print(D)
  5. # Much faster with scipy
  6. import scipy
  7. # Thanks Gavin Heverly-Coulson (#issue 1)
  8. import scipy.spatial
  9. Z = np.random.random((10,2))
  10. D = scipy.spatial.distance.cdist(Z,Z)
  11. print(D)

53. How to convert a float (32 bits) array into an integer (32 bits) in place?

  1. # Thanks Vikas (https://stackoverflow.com/a/10622758/5989906)
  2. # & unutbu (https://stackoverflow.com/a/4396247/5989906)
  3. Z = (np.random.rand(10)*100).astype(np.float32)
  4. Y = Z.view(np.int32)
  5. Y[:] = Z
  6. print(Y)

54. How to read the following file? (★★☆)

  1. 1, 2, 3, 4, 5
  2. 6, , , 7, 8
  3. , , 9,10,11
  1. from io import StringIO
  2. # Fake file
  3. s = StringIO('''1, 2, 3, 4, 5
  4. 6, , , 7, 8
  5. , , 9,10,11
  6. ''')
  7. Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
  8. print(Z)

55. What is the equivalent of enumerate for numpy arrays? (★★☆)

  1. Z = np.arange(9).reshape(3,3)
  2. for index, value in np.ndenumerate(Z):
  3. print(index, value)
  4. for index in np.ndindex(Z.shape):
  5. print(index, Z[index])

56. Generate a generic 2D Gaussian-like array (★★☆)

  1. X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
  2. D = np.sqrt(X*X+Y*Y)
  3. sigma, mu = 1.0, 0.0
  4. G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
  5. print(G)

57. How to randomly place p elements in a 2D array? (★★☆)

  1. # Author: Divakar
  2. n = 10
  3. p = 3
  4. Z = np.zeros((n,n))
  5. np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
  6. print(Z)

58. Subtract the mean of each row of a matrix (★★☆)

  1. # Author: Warren Weckesser
  2. X = np.random.rand(5, 10)
  3. # Recent versions of numpy
  4. Y = X - X.mean(axis=1, keepdims=True)
  5. # Older versions of numpy
  6. Y = X - X.mean(axis=1).reshape(-1, 1)
  7. print(Y)

59. How to sort an array by the nth column? (★★☆)

  1. # Author: Steve Tjoa
  2. Z = np.random.randint(0,10,(3,3))
  3. print(Z)
  4. print(Z[Z[:,1].argsort()])

60. How to tell if a given 2D array has null columns? (★★☆)

  1. # Author: Warren Weckesser
  2. Z = np.random.randint(0,3,(3,10))
  3. print((~Z.any(axis=0)).any())

61. Find the nearest value from a given value in an array (★★☆)

  1. Z = np.random.uniform(0,1,10)
  2. z = 0.5
  3. m = Z.flat[np.abs(Z - z).argmin()]
  4. print(m)

62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)

  1. A = np.arange(3).reshape(3,1)
  2. B = np.arange(3).reshape(1,3)
  3. it = np.nditer([A,B,None])
  4. for x,y,z in it: z[...] = x + y
  5. print(it.operands[2])

63. Create an array class that has a name attribute (★★☆)

  1. class NamedArray(np.ndarray):
  2. def __new__(cls, array, name="no name"):
  3. obj = np.asarray(array).view(cls)
  4. obj.name = name
  5. return obj
  6. def __array_finalize__(self, obj):
  7. if obj is None: return
  8. self.info = getattr(obj, 'name', "no name")
  9. Z = NamedArray(np.arange(10), "range_10")
  10. print (Z.name)

64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)

  1. # Author: Brett Olsen
  2. Z = np.ones(10)
  3. I = np.random.randint(0,len(Z),20)
  4. Z += np.bincount(I, minlength=len(Z))
  5. print(Z)
  6. # Another solution
  7. # Author: Bartosz Telenczuk
  8. np.add.at(Z, I, 1)
  9. print(Z)

65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)

  1. # Author: Alan G Isaac
  2. X = [1,2,3,4,5,6]
  3. I = [1,3,9,3,4,1]
  4. F = np.bincount(I,X)
  5. print(F)

66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)

  1. # Author: Fisher Wang
  2. w, h = 256, 256
  3. I = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte)
  4. colors = np.unique(I.reshape(-1, 3), axis=0)
  5. n = len(colors)
  6. print(n)
  7. # Faster version
  8. # Author: Mark Setchell
  9. # https://stackoverflow.com/a/59671950/2836621
  10. w, h = 256, 256
  11. I = np.random.randint(0,4,(h,w,3), dtype=np.uint8)
  12. # View each pixel as a single 24-bit integer, rather than three 8-bit bytes
  13. I24 = np.dot(I.astype(np.uint32),[1,256,65536])
  14. # Count unique colours
  15. n = len(np.unique(I24))
  16. print(n)

67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)

  1. A = np.random.randint(0,10,(3,4,3,4))
  2. # solution by passing a tuple of axes (introduced in numpy 1.7.0)
  3. sum = A.sum(axis=(-2,-1))
  4. print(sum)
  5. # solution by flattening the last two dimensions into one
  6. # (useful for functions that don't accept tuples for axis argument)
  7. sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
  8. 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? (★★★)

  1. # Author: Jaime Fernández del Río
  2. D = np.random.uniform(0,1,100)
  3. S = np.random.randint(0,10,100)
  4. D_sums = np.bincount(S, weights=D)
  5. D_counts = np.bincount(S)
  6. D_means = D_sums / D_counts
  7. print(D_means)
  8. # Pandas solution as a reference due to more intuitive code
  9. import pandas as pd
  10. print(pd.Series(D).groupby(S).mean())

69. How to get the diagonal of a dot product? (★★★)

  1. # Author: Mathieu Blondel
  2. A = np.random.uniform(0,1,(5,5))
  3. B = np.random.uniform(0,1,(5,5))
  4. # Slow version
  5. np.diag(np.dot(A, B))
  6. # Fast version
  7. np.sum(A * B.T, axis=1)
  8. # Faster version
  9. 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? (★★★)

  1. # Author: Warren Weckesser
  2. Z = np.array([1,2,3,4,5])
  3. nz = 3
  4. Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
  5. Z0[::nz+1] = Z
  6. print(Z0)

71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)

  1. A = np.ones((5,5,3))
  2. B = 2*np.ones((5,5))
  3. print(A * B[:,:,None])

72. How to swap two rows of an array? (★★★)

  1. # Author: Eelco Hoogendoorn
  2. A = np.arange(25).reshape(5,5)
  3. A[[0,1]] = A[[1,0]]
  4. 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 (★★★)

  1. # Author: Nicolas P. Rougier
  2. faces = np.random.randint(0,100,(10,3))
  3. F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
  4. F = F.reshape(len(F)*3,2)
  5. F = np.sort(F,axis=1)
  6. G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
  7. G = np.unique(G)
  8. 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? (★★★)

  1. # Author: Jaime Fernández del Río
  2. C = np.bincount([1,1,2,3,4,4,6])
  3. A = np.repeat(np.arange(len(C)), C)
  4. print(A)

75. How to compute averages using a sliding window over an array? (★★★)

  1. # Author: Jaime Fernández del Río
  2. def moving_average(a, n=3) :
  3. ret = np.cumsum(a, dtype=float)
  4. ret[n:] = ret[n:] - ret[:-n]
  5. return ret[n - 1:] / n
  6. Z = np.arange(20)
  7. print(moving_average(Z, n=3))
  8. # Author: Jeff Luo (@Jeff1999)
  9. # make sure your NumPy >= 1.20.0
  10. from numpy.lib.stride_tricks import sliding_window_view
  11. Z = np.arange(20)
  12. 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]) (★★★)

  1. # Author: Joe Kington / Erik Rigtorp
  2. from numpy.lib import stride_tricks
  3. def rolling(a, window):
  4. shape = (a.size - window + 1, window)
  5. strides = (a.strides[0], a.strides[0])
  6. return stride_tricks.as_strided(a, shape=shape, strides=strides)
  7. Z = rolling(np.arange(10), 3)
  8. print(Z)
  9. # Author: Jeff Luo (@Jeff1999)
  10. Z = np.arange(10)
  11. print(sliding_window_view(Z, window_shape=3))

77. How to negate a boolean, or to change the sign of a float inplace? (★★★)

  1. # Author: Nathaniel J. Smith
  2. Z = np.random.randint(0,2,100)
  3. np.logical_not(Z, out=Z)
  4. Z = np.random.uniform(-1.0,1.0,100)
  5. 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])? (★★★)

  1. def distance(P0, P1, p):
  2. T = P1 - P0
  3. L = (T**2).sum(axis=1)
  4. U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
  5. U = U.reshape(len(U),1)
  6. D = P0 + U*T - p
  7. return np.sqrt((D**2).sum(axis=1))
  8. P0 = np.random.uniform(-10,10,(10,2))
  9. P1 = np.random.uniform(-10,10,(10,2))
  10. p = np.random.uniform(-10,10,( 1,2))
  11. print(distance(P0, P1, p))

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])? (★★★)

  1. # Author: Italmassov Kuanysh
  2. # based on distance function from previous question
  3. P0 = np.random.uniform(-10, 10, (10,2))
  4. P1 = np.random.uniform(-10,10,(10,2))
  5. p = np.random.uniform(-10, 10, (10,2))
  6. 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) (★★★)

  1. # Author: Nicolas Rougier
  2. Z = np.random.randint(0,10,(10,10))
  3. shape = (5,5)
  4. fill = 0
  5. position = (1,1)
  6. R = np.ones(shape, dtype=Z.dtype)*fill
  7. P = np.array(list(position)).astype(int)
  8. Rs = np.array(list(R.shape)).astype(int)
  9. Zs = np.array(list(Z.shape)).astype(int)
  10. R_start = np.zeros((len(shape),)).astype(int)
  11. R_stop = np.array(list(shape)).astype(int)
  12. Z_start = (P-Rs//2)
  13. Z_stop = (P+Rs//2)+Rs%2
  14. R_start = (R_start - np.minimum(Z_start,0)).tolist()
  15. Z_start = (np.maximum(Z_start,0)).tolist()
  16. R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
  17. Z_stop = (np.minimum(Z_stop,Zs)).tolist()
  18. r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
  19. z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
  20. R[r] = Z[z]
  21. print(Z)
  22. 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]]? (★★★)

  1. # Author: Stefan van der Walt
  2. Z = np.arange(1,15,dtype=np.uint32)
  3. R = stride_tricks.as_strided(Z,(11,4),(4,4))
  4. print(R)
  5. # Author: Jeff Luo (@Jeff1999)
  6. Z = np.arange(1, 15, dtype=np.uint32)
  7. print(sliding_window_view(Z, window_shape=4))

82. Compute a matrix rank (★★★)

  1. # Author: Stefan van der Walt
  2. Z = np.random.uniform(0,1,(10,10))
  3. U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
  4. rank = np.sum(S > 1e-10)
  5. print(rank)
  6. # alternative solution:
  7. # Author: Jeff Luo (@Jeff1999)
  8. rank = np.linalg.matrix_rank(Z)
  9. print(rank)

83. How to find the most frequent value in an array?

  1. Z = np.random.randint(0,10,50)
  2. print(np.bincount(Z).argmax())

84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)

  1. # Author: Chris Barker
  2. Z = np.random.randint(0,5,(10,10))
  3. n = 3
  4. i = 1 + (Z.shape[0]-3)
  5. j = 1 + (Z.shape[1]-3)
  6. C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)
  7. print(C)
  8. # Author: Jeff Luo (@Jeff1999)
  9. Z = np.random.randint(0,5,(10,10))
  10. print(sliding_window_view(Z, window_shape=(3, 3)))

85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)

  1. # Author: Eric O. Lebigot
  2. # Note: only works for 2d array and value setting using indices
  3. class Symetric(np.ndarray):
  4. def __setitem__(self, index, value):
  5. i,j = index
  6. super(Symetric, self).__setitem__((i,j), value)
  7. super(Symetric, self).__setitem__((j,i), value)
  8. def symetric(Z):
  9. return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)
  10. S = symetric(np.random.randint(0,10,(5,5)))
  11. S[2,3] = 42
  12. 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)) (★★★)

  1. # Author: Stefan van der Walt
  2. p, n = 10, 20
  3. M = np.ones((p,n,n))
  4. V = np.ones((p,n,1))
  5. S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
  6. print(S)
  7. # It works, because:
  8. # M is (p,n,n)
  9. # V is (p,n,1)
  10. # Thus, summing over the paired axes 0 and 0 (of M and V independently),
  11. # 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)? (★★★)

  1. # Author: Robert Kern
  2. Z = np.ones((16,16))
  3. k = 4
  4. S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
  5. np.arange(0, Z.shape[1], k), axis=1)
  6. print(S)
  7. # alternative solution:
  8. # Author: Sebastian Wallkötter (@FirefoxMetzger)
  9. Z = np.ones((16,16))
  10. k = 4
  11. windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
  12. S = windows[::k, ::k, ...].sum(axis=(-2, -1))
  13. # Author: Jeff Luo (@Jeff1999)
  14. Z = np.ones((16, 16))
  15. k = 4
  16. print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))

88. How to implement the Game of Life using numpy arrays? (★★★)

  1. # Author: Nicolas Rougier
  2. def iterate(Z):
  3. # Count neighbours
  4. N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +
  5. Z[1:-1,0:-2] + Z[1:-1,2:] +
  6. Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])
  7. # Apply rules
  8. birth = (N==3) & (Z[1:-1,1:-1]==0)
  9. survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)
  10. Z[...] = 0
  11. Z[1:-1,1:-1][birth | survive] = 1
  12. return Z
  13. Z = np.random.randint(0,2,(50,50))
  14. for i in range(100): Z = iterate(Z)
  15. print(Z)

89. How to get the n largest values of an array (★★★)

  1. Z = np.arange(10000)
  2. np.random.shuffle(Z)
  3. n = 5
  4. # Slow
  5. print (Z[np.argsort(Z)[-n:]])
  6. # Fast
  7. print (Z[np.argpartition(-Z,n)[:n]])

90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)

  1. # Author: Stefan Van der Walt
  2. def cartesian(arrays):
  3. arrays = [np.asarray(a) for a in arrays]
  4. shape = (len(x) for x in arrays)
  5. ix = np.indices(shape, dtype=int)
  6. ix = ix.reshape(len(arrays), -1).T
  7. for n, arr in enumerate(arrays):
  8. ix[:, n] = arrays[n][ix[:, n]]
  9. return ix
  10. print (cartesian(([1, 2, 3], [4, 5], [6, 7])))

91. How to create a record array from a regular array? (★★★)

  1. Z = np.array([("Hello", 2.5, 3),
  2. ("World", 3.6, 2)])
  3. R = np.core.records.fromarrays(Z.T,
  4. names='col1, col2, col3',
  5. formats = 'S8, f8, i8')
  6. print(R)

92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)

  1. # Author: Ryan G.
  2. x = np.random.rand(int(5e7))
  3. %timeit np.power(x,3)
  4. %timeit x*x*x
  5. %timeit np.einsum('i,i,i->i',x,x,x)

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? (★★★)

  1. # Author: Gabe Schwartz
  2. A = np.random.randint(0,5,(8,3))
  3. B = np.random.randint(0,5,(2,2))
  4. C = (A[..., np.newaxis, np.newaxis] == B)
  5. rows = np.where(C.any((3,1)).all(1))[0]
  6. print(rows)

94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)

  1. # Author: Robert Kern
  2. Z = np.random.randint(0,5,(10,3))
  3. print(Z)
  4. # solution for arrays of all dtypes (including string arrays and record arrays)
  5. E = np.all(Z[:,1:] == Z[:,:-1], axis=1)
  6. U = Z[~E]
  7. print(U)
  8. # soluiton for numerical arrays only, will work for any number of columns in Z
  9. U = Z[Z.max(axis=1) != Z.min(axis=1),:]
  10. print(U)

95. Convert a vector of ints into a matrix binary representation (★★★)

  1. # Author: Warren Weckesser
  2. I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
  3. B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
  4. print(B[:,::-1])
  5. # Author: Daniel T. McDonald
  6. I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
  7. print(np.unpackbits(I[:, np.newaxis], axis=1))

96. Given a two dimensional array, how to extract unique rows? (★★★)

  1. # Author: Jaime Fernández del Río
  2. Z = np.random.randint(0,2,(6,3))
  3. T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))
  4. _, idx = np.unique(T, return_index=True)
  5. uZ = Z[idx]
  6. print(uZ)
  7. # Author: Andreas Kouzelis
  8. # NumPy >= 1.13
  9. uZ = np.unique(Z, axis=0)
  10. print(uZ)

97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)

  1. # Author: Alex Riley
  2. # Make sure to read: http://ajcr.net/Basic-guide-to-einsum/
  3. A = np.random.uniform(0,1,10)
  4. B = np.random.uniform(0,1,10)
  5. np.einsum('i->', A) # np.sum(A)
  6. np.einsum('i,i->i', A, B) # A * B
  7. np.einsum('i,i', A, B) # np.inner(A, B)
  8. np.einsum('i,j->ij', A, B) # np.outer(A, B)

98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?

  1. # Author: Bas Swinckels
  2. phi = np.arange(0, 10*np.pi, 0.1)
  3. a = 1
  4. x = a*phi*np.cos(phi)
  5. y = a*phi*np.sin(phi)
  6. dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths
  7. r = np.zeros_like(x)
  8. r[1:] = np.cumsum(dr) # integrate path
  9. r_int = np.linspace(0, r.max(), 200) # regular spaced path
  10. x_int = np.interp(r_int, r, x) # integrate path
  11. y_int = np.interp(r_int, r, y)

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. (★★★)

  1. # Author: Evgeni Burovski
  2. X = np.asarray([[1.0, 0.0, 3.0, 8.0],
  3. [2.0, 0.0, 1.0, 1.0],
  4. [1.5, 2.5, 1.0, 0.0]])
  5. n = 4
  6. M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
  7. M &= (X.sum(axis=-1) == n)
  8. 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). (★★★)

  1. # Author: Jessica B. Hamrick
  2. X = np.random.randn(100) # random 1D array
  3. N = 1000 # number of bootstrap samples
  4. idx = np.random.randint(0, X.size, (N, X.size))
  5. means = X[idx].mean(axis=1)
  6. confint = np.percentile(means, [2.5, 97.5])
  7. print(confint)