100 Numpy Exercises


title: "Alternative solution, in Python 3.5 and above" date: 2026-05-24T13:50:37Z

100 numpy exercises

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

1. Import the numpy package under the name np (★☆☆)

1import numpy as np

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

1print(np.__version__)
2np.show_config()
1.14.2
mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']
blas_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']
blas_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']
lapack_mkl_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']
lapack_opt_info:
    libraries = ['mkl_rt']
    library_dirs = ['C:/ProgramData/Anaconda3\\Library\\lib']
    define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
    include_dirs = ['C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\include', 'C:\\Program Files (x86)\\IntelSWTools\\compilers_and_libraries_2016.4.246\\windows\\mkl\\lib', 'C:/ProgramData/Anaconda3\\Library\\include']

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

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

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

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

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)"`
ERROR:root:File `'`python.py'` not found.

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

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

NameError                                 Traceback (most recent call last)

<ipython-input-1-3ad7d656eb82> in <module>()
----> 1 Z = np.zeros(10)
      2 Z[4] = 1
      3 print(Z)


NameError: name 'np' is not defined

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

1Z = np.arange(10,50)
2print(Z)
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]

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

1Z = np.arange(50)
2Z = Z[::-1]
3print(Z)
[49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26
 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2
  1  0]

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

1Z = np.arange(9).reshape(3,3)
2print(Z)
[[0 1 2]
 [3 4 5]
 [6 7 8]]

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

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

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

1Z = np.eye(3)
2print(Z)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

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

1Z = np.random.random((3,3,3))
2print(Z)
[[[0.38623687 0.72860689 0.11861256]
  [0.87583184 0.75984112 0.92027858]
  [0.15569262 0.24601167 0.40514924]]

 [[0.23179978 0.41058658 0.97117928]
  [0.76418077 0.5534301  0.52208481]
  [0.6620278  0.92392492 0.58433957]]

 [[0.14777566 0.83096875 0.20888782]
  [0.94630753 0.14862539 0.88969933]
  [0.10930963 0.13027745 0.41575222]]]

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

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

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

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

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

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

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

1Z = np.ones((5,5))
2Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
3print(Z)
[[0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 1. 1. 1. 1. 1. 0.]
 [0. 0. 0. 0. 0. 0. 0.]]

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

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

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

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

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

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

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

1print(np.unravel_index(100,(6,7,8)))
(1, 5, 4)

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

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

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

1Z = np.random.random((5,5))
2Z = (Z - np.mean (Z)) / (np.std (Z))
3print(Z)
[[ 0.60460987  1.57268218 -0.89575026  0.39473056 -1.03035535]
 [ 0.48811681  0.27544473 -0.44867393  0.29267064 -0.68241891]
 [-0.3952934  -1.05912252 -1.38505776  0.35666151  0.27154967]
 [-1.11291754 -1.55657621  1.41843066  1.9689818   0.90553902]
 [-0.50662642 -0.47622473 -1.01864733  0.07395656  1.94429034]]

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

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

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

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

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

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

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

1# Author: Jake VanderPlas
2
3print(sum(range(5),-1))
4from numpy import *
5print(sum(range(5),-1))
9
10
1Z**Z
22 << Z >> 2
3Z <- Z
41j*Z
5Z/1/1
6Z<Z>Z
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-27-4e3654d03fce> in <module>()
----> 1 Z**Z
      2 2 << Z >> 2
      3 Z <- Z
      4 1j*Z
      5 Z/1/1


ValueError: Integers to negative integer powers are not allowed.

28. What are the result of the following expressions?

1print(np.array(0) / np.array(0))
2print(np.array(0) // np.array(0))
3print(np.array([np.nan]).astype(int).astype(float))
nan
0
[-2.14748365e+09]


C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in true_divide
  """Entry point for launching an IPython kernel.
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in floor_divide

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

1# Author: Charles R Harris
2
3Z = np.random.uniform(-10,+10,10)
4print (np.copysign(np.ceil(np.abs(Z)), Z))
[ 6.  6.  8. -9.  7. -9.  9.  8.  2.  4.]

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

1Z1 = np.random.randint(0,10,10)
2Z2 = np.random.randint(0,10,10)
3print(np.intersect1d(Z1,Z2))
[0 2]
 1# Suicide mode on
 2defaults = np.seterr(all="ignore")
 3Z = np.ones(1) / 0
 4
 5# Back to sanity
 6_ = np.seterr(**defaults)
 7
 8An equivalent way, with a context manager:
 9
10with np.errstate(divide='ignore'):
11    Z = np.ones(1) / 0
  File "<ipython-input-31-0437b6d2f8fa>", line 8
    An equivalent way, with a context manager:
                ^
SyntaxError: invalid syntax

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

1np.sqrt(-1) == np.emath.sqrt(-1)
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in sqrt
  """Entry point for launching an IPython kernel.





False

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

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

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

1Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
2print(Z)
['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05'
 '2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10'
 '2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15'
 '2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20'
 '2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25'
 '2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30'
 '2016-07-31']

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

1A = np.ones(3)*1
2B = np.ones(3)*2
3C = np.ones(3)*3
4np.add(A,B,out=B)
5np.divide(A,2,out=A)
6np.negative(A,out=A)
7np.multiply(A,B,out=A)
array([-1.5, -1.5, -1.5])

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

1Z = np.random.uniform(0,10,10)
2
3print (Z - Z%1)
4print (np.floor(Z))
5print (np.ceil(Z)-1)
6print (Z.astype(int))
7print (np.trunc(Z))
[0. 9. 9. 7. 4. 5. 8. 7. 9. 6.]
[0. 9. 9. 7. 4. 5. 8. 7. 9. 6.]
[0. 9. 9. 7. 4. 5. 8. 7. 9. 6.]
[0 9 9 7 4 5 8 7 9 6]
[0. 9. 9. 7. 4. 5. 8. 7. 9. 6.]

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

1Z = np.zeros((5,5))
2Z += np.arange(5)
3print(Z)
[[0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]]

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

1def generate():
2    for x in range(10):
3        yield x
4Z = np.fromiter(generate(),dtype=float,count=-1)
5print(Z)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]

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

1Z = np.linspace(0,1,11,endpoint=False)[1:]
2print(Z)
[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
 0.63636364 0.72727273 0.81818182 0.90909091]

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

1Z = np.random.random(10)
2Z.sort()
3print(Z)
[0.10181103 0.26965266 0.28134397 0.39484134 0.41394065 0.4810561
 0.62636945 0.74893964 0.88528826 0.97455845]

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

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

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

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

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

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

ValueError                                Traceback (most recent call last)

<ipython-input-43-dcc5e7f145b5> in <module>()
      1 Z = np.zeros(10)
      2 Z.flags.writeable = False
----> 3 Z[0] = 1


ValueError: assignment destination is read-only

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

1Z = np.random.random((10,2))
2X,Y = Z[:,0], Z[:,1]
3R = np.sqrt(X**2+Y**2)
4T = np.arctan2(Y,X)
5print(R)
6print(T)
[0.90871086 0.46968371 0.33413258 0.71420399 0.59422443 1.05019902
 0.83054677 0.79518205 0.86608232 1.03318804]
[1.39381095 0.5465867  0.38210814 0.60935469 0.126408   0.87938679
 1.28469889 1.51565796 0.02201551 0.36169143]

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

1Z = np.random.random(10)
2Z[Z.argmax()] = 0
3print(Z)
[0.50581524 0.25651855 0.01674091 0.88347224 0.73571427 0.44169975
 0.65173587 0.84419501 0.         0.70272942]

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

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

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

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

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

1for dtype in [np.int8, np.int32, np.int64]:
2   print(np.iinfo(dtype).min)
3   print(np.iinfo(dtype).max)
4for dtype in [np.float32, np.float64]:
5   print(np.finfo(dtype).min)
6   print(np.finfo(dtype).max)
7   print(np.finfo(dtype).eps)
-128
127
-2147483648
2147483647
-9223372036854775808
9223372036854775807
-3.4028235e+38
3.4028235e+38
1.1920929e-07
-1.7976931348623157e+308
1.7976931348623157e+308
2.220446049250313e-16

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

1np.set_printoptions(threshold=np.nan)
2Z = np.zeros((16,16))
3print(Z)
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

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

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

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

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

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

 1Z = np.random.random((10,2))
 2X,Y = np.atleast_2d(Z[:,0], Z[:,1])
 3D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
 4print(D)
 5
 6# Much faster with scipy
 7import scipy
 8# Thanks Gavin Heverly-Coulson (#issue 1)
 9import scipy.spatial
10
11Z = np.random.random((10,2))
12D = scipy.spatial.distance.cdist(Z,Z)
13print(D)
[[0.         0.70858175 0.65599073 0.78907021 0.03919281 0.58217916
  0.33731228 0.7468501  0.81072821 0.34085638]
 [0.70858175 0.         0.59344529 0.09512034 0.71317592 0.25956344
  0.80803137 0.53153655 0.36521195 0.63714484]
 [0.65599073 0.59344529 0.         0.68051235 0.62827887 0.33895441
  0.46987665 0.13920127 0.34746751 0.3316422 ]
 [0.78907021 0.09512034 0.68051235 0.         0.79617326 0.35163036
  0.90195864 0.60906462 0.4231078  0.73188727]
 [0.03919281 0.71317592 0.62827887 0.79617326 0.         0.5731727
  0.29812293 0.72361492 0.79714149 0.30801574]
 [0.58217916 0.25956344 0.33895441 0.35163036 0.5731727  0.
  0.58754608 0.30460826 0.24114521 0.40949401]
 [0.33731228 0.80803137 0.46987665 0.90195864 0.29812293 0.58754608
  0.         0.59944019 0.75065963 0.17852171]
 [0.7468501  0.53153655 0.13920127 0.60906462 0.72361492 0.30460826
  0.59944019 0.         0.22570191 0.44636568]
 [0.81072821 0.36521195 0.34746751 0.4231078  0.79714149 0.24114521
  0.75065963 0.22570191 0.         0.57714969]
 [0.34085638 0.63714484 0.3316422  0.73188727 0.30801574 0.40949401
  0.17852171 0.44636568 0.57714969 0.        ]]
[[0.         0.21528274 0.6433255  0.33437612 0.28776324 0.14819688
  0.34321379 0.54524259 0.68307656 0.0830019 ]
 [0.21528274 0.         0.44712729 0.27403285 0.32591639 0.28524061
  0.33478698 0.35128389 0.49450395 0.16691601]
 [0.6433255  0.44712729 0.         0.41503631 0.74613255 0.73233626
  0.49409743 0.41928663 0.49963719 0.61255203]
 [0.33437612 0.27403285 0.41503631 0.         0.57318081 0.47403049
  0.08658329 0.56115111 0.70031091 0.35760984]
 [0.28776324 0.32591639 0.74613255 0.57318081 0.         0.16110392
  0.60777831 0.46777708 0.57012915 0.22441559]
 [0.14819688 0.28524061 0.73233626 0.47403049 0.16110392 0.
  0.49018431 0.54358417 0.66733094 0.12437018]
 [0.34321379 0.33478698 0.49409743 0.08658329 0.60777831 0.49018431
  0.         0.64241387 0.78297501 0.38468325]
 [0.54524259 0.35128389 0.41928663 0.56115111 0.46777708 0.54358417
  0.64241387 0.         0.14386424 0.470974  ]
 [0.68307656 0.49450395 0.49963719 0.70031091 0.57012915 0.66733094
  0.78297501 0.14386424 0.         0.60610333]
 [0.0830019  0.16691601 0.61255203 0.35760984 0.22441559 0.12437018
  0.38468325 0.470974   0.60610333 0.        ]]

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

1Z = np.arange(10, dtype=np.float32)
2Z = Z.astype(np.int32, copy=False)
3print(Z)
[0 1 2 3 4 5 6 7 8 9]

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

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

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

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

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

1X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
2D = np.sqrt(X*X+Y*Y)
3sigma, mu = 1.0, 0.0
4G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
5print(G)
[[0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818
  0.57375342 0.51979489 0.44822088 0.36787944]
 [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367
  0.69905581 0.63331324 0.54610814 0.44822088]
 [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308
  0.81068432 0.73444367 0.63331324 0.51979489]
 [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382  0.9401382
  0.89483932 0.81068432 0.69905581 0.57375342]
 [0.60279818 0.73444367 0.85172308 0.9401382  0.98773022 0.98773022
  0.9401382  0.85172308 0.73444367 0.60279818]
 [0.60279818 0.73444367 0.85172308 0.9401382  0.98773022 0.98773022
  0.9401382  0.85172308 0.73444367 0.60279818]
 [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382  0.9401382
  0.89483932 0.81068432 0.69905581 0.57375342]
 [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308
  0.81068432 0.73444367 0.63331324 0.51979489]
 [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367
  0.69905581 0.63331324 0.54610814 0.44822088]
 [0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818
  0.57375342 0.51979489 0.44822088 0.36787944]]

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

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

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

 1# Author: Warren Weckesser
 2
 3X = np.random.rand(5, 10)
 4
 5# Recent versions of numpy
 6Y = X - X.mean(axis=1, keepdims=True)
 7
 8# Older versions of numpy
 9Y = X - X.mean(axis=1).reshape(-1, 1)
10
11print(Y)
[[ 0.08728985  0.34574179 -0.07096404 -0.35665903  0.27195823 -0.21226241
  -0.05786562  0.46226838 -0.51113477  0.04162763]
 [ 0.15769693 -0.00687416 -0.23088468 -0.27531393 -0.15748372  0.49855641
  -0.29182386  0.23153223  0.1335274  -0.05893261]
 [-0.19887161 -0.08551958  0.13483777  0.4249683   0.32140219 -0.01568819
  -0.25863495 -0.19687856  0.0745396  -0.20015498]
 [ 0.05544274  0.23450517 -0.25309467  0.00991447 -0.50428326 -0.09024474
   0.01610101  0.4324277   0.13499273 -0.03576114]
 [ 0.08014561  0.44307603 -0.54198293 -0.15386254  0.377373    0.24122398
  -0.4620369  -0.03100136  0.21078297 -0.16371787]]

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

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

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

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

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

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

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

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

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

 1class 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
10Z = NamedArray(np.arange(10), "range_10")
11print (Z.name)
range_10

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
 3Z = np.ones(10)
 4I = np.random.randint(0,len(Z),20)
 5Z += np.bincount(I, minlength=len(Z))
 6print(Z)
 7
 8# Another solution
 9# Author: Bartosz Telenczuk
10np.add.at(Z, I, 1)
11print(Z)
[2. 5. 4. 1. 1. 4. 3. 2. 5. 3.]
[3. 9. 7. 1. 1. 7. 5. 3. 9. 5.]

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
3X = [1,2,3,4,5,6]
4I = [1,3,9,3,4,1]
5F = np.bincount(I,X)
6print(F)
[0. 7. 0. 6. 5. 0. 0. 0. 0. 3.]

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

1# Author: Nadav Horesh
2
3w,h = 16,16
4I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
5#Note that we should compute 256*256 first. 
6#Otherwise numpy will only promote F.dtype to 'uint16' and overfolw will occur
7F = I[...,0]*(256*256) + I[...,1]*256 +I[...,2]
8n = len(np.unique(F))
9print(n)
8

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

1A = np.random.randint(0,10,(3,4,3,4))
2# solution by passing a tuple of axes (introduced in numpy 1.7.0)
3sum = A.sum(axis=(-2,-1))
4print(sum)
5# solution by flattening the last two dimensions into one
6# (useful for functions that don't accept tuples for axis argument)
7sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
8print(sum)
[[67 54 59 65]
 [71 59 49 46]
 [40 46 48 44]]
[[67 54 59 65]
 [71 59 49 46]
 [40 46 48 44]]

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
 3D = np.random.uniform(0,1,100)
 4S = np.random.randint(0,10,100)
 5D_sums = np.bincount(S, weights=D)
 6D_counts = np.bincount(S)
 7D_means = D_sums / D_counts
 8print(D_means)
 9
10# Pandas solution as a reference due to more intuitive code
11import pandas as pd
12print(pd.Series(D).groupby(S).mean())
[0.36435063 0.49399621 0.41187814 0.55834713 0.50337821 0.59980105
 0.54636651 0.62150694 0.46052147 0.55536347]
0    0.364351
1    0.493996
2    0.411878
3    0.558347
4    0.503378
5    0.599801
6    0.546367
7    0.621507
8    0.460521
9    0.555363
dtype: float64

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

 1# Author: Mathieu Blondel
 2
 3A = np.random.uniform(0,1,(5,5))
 4B = np.random.uniform(0,1,(5,5))
 5
 6# Slow version  
 7np.diag(np.dot(A, B))
 8
 9# Fast version
10np.sum(A * B.T, axis=1)
11
12# Faster version
13np.einsum("ij,ji->i", A, B)
array([1.43740433, 1.30533245, 1.32379824, 2.46896817, 0.67545867])

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
3Z = np.array([1,2,3,4,5])
4nz = 3
5Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
6Z0[::nz+1] = Z
7print(Z0)
[1. 0. 0. 0. 2. 0. 0. 0. 3. 0. 0. 0. 4. 0. 0. 0. 5.]

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

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

 [[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]

 [[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]

 [[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]

 [[2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]
  [2. 2. 2.]]]

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

1# Author: Eelco Hoogendoorn
2
3A = np.arange(25).reshape(5,5)
4A[[0,1]] = A[[1,0]]
5print(A)
[[ 5  6  7  8  9]
 [ 0  1  2  3  4]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

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
3faces = np.random.randint(0,100,(10,3))
4F = np.roll(faces.repeat(2,axis=1),-1,axis=1)
5F = F.reshape(len(F)*3,2)
6F = np.sort(F,axis=1)
7G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )
8G = np.unique(G)
9print(G)
[( 0,  9) ( 0, 11) ( 0, 59) ( 0, 91) ( 1,  8) ( 1, 47) ( 1, 69) ( 1, 82)
 ( 3, 40) ( 3, 97) ( 5,  9) ( 5, 73) ( 8, 47) ( 9, 11) ( 9, 73) (13, 53)
 (13, 56) (13, 58) (13, 99) (16, 62) (16, 82) (28, 84) (28, 87) (40, 97)
 (53, 99) (56, 58) (59, 91) (62, 82) (69, 82) (84, 87)]

74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)

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

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

1# Author: Jaime Fernández del Río
2
3def moving_average(a, n=3) :
4    ret = np.cumsum(a, dtype=float)
5    ret[n:] = ret[n:] - ret[:-n]
6    return ret[n - 1:] / n
7Z = np.arange(20)
8print(moving_average(Z, n=3))
[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18.]

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
2from numpy.lib import stride_tricks
3
4def rolling(a, window):
5    shape = (a.size - window + 1, window)
6    strides = (a.itemsize, a.itemsize)
7    return stride_tricks.as_strided(a, shape=shape, strides=strides)
8Z = rolling(np.arange(10), 3)
9print(Z)
[[0 1 2]
 [1 2 3]
 [2 3 4]
 [3 4 5]
 [4 5 6]
 [5 6 7]
 [6 7 8]
 [7 8 9]]

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

1# Author: Nathaniel J. Smith
2
3Z = np.random.randint(0,2,100)
4np.logical_not(Z, out=Z)
5
6Z = np.random.uniform(-1.0,1.0,100)
7np.negative(Z, out=Z)
array([ 0.61458663, -0.83229834,  0.15687329,  0.86684934, -0.80418945,
       -0.94400753,  0.68204938, -0.40034997,  0.56881214,  0.60763882,
       -0.41558119, -0.96786492, -0.29382729, -0.43597838,  0.46867397,
       -0.73113098, -0.31367014,  0.50218112, -0.18159377, -0.03321331,
        0.93574029,  0.95764592,  0.83438669,  0.93493816,  0.27413529,
        0.79686667,  0.21453622, -0.34477178, -0.90442065, -0.28982899,
       -0.22376251,  0.7821683 ,  0.80871286,  0.09547893,  0.65898887,
       -0.50329235,  0.70567483,  0.7260582 ,  0.29526807, -0.61692596,
       -0.06398481,  0.38447694, -0.20192775, -0.776956  , -0.86298302,
        0.62069504,  0.7156818 , -0.16731062, -0.67338785,  0.9475525 ,
        0.78363151, -0.68028943,  0.37714017,  0.99798309,  0.09080988,
        0.22431419,  0.44528906,  0.27134833, -0.17727835, -0.64134425,
       -0.26404034, -0.10714442,  0.04077127,  0.76593247, -0.26830685,
        0.81933781, -0.14372722, -0.78525057, -0.03657832, -0.0838801 ,
       -0.9998223 , -0.57809221,  0.62441487, -0.91798214, -0.20347455,
        0.89401068, -0.36615874,  0.35508649, -0.988561  , -0.42155252,
       -0.79222461, -0.38832939,  0.65991297,  0.09981309, -0.26838381,
       -0.61731762,  0.470328  ,  0.36521011, -0.04780786,  0.52860473,
        0.44800137,  0.18834723, -0.90079054, -0.03385857,  0.72054287,
        0.98253035, -0.93777418,  0.86997239,  0.98122332, -0.4601323 ])

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

 1def 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
 9P0 = np.random.uniform(-10,10,(10,2))
10P1 = np.random.uniform(-10,10,(10,2))
11p  = np.random.uniform(-10,10,( 1,2))
12print(distance(P0, P1, p))
[3.70672797 7.69612039 2.25784974 4.60168732 1.86333395 0.34324433
 0.81905363 1.00428102 4.4882624  5.52240104]

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
3# based on distance function from previous question
4P0 = np.random.uniform(-10, 10, (10,2))
5P1 = np.random.uniform(-10,10,(10,2))
6p = np.random.uniform(-10, 10, (10,2))
7print(np.array([distance(P0,P1,p_i) for p_i in p]))
[[ 3.51631169  6.42167595  4.90471349  8.92152608  0.64430522 13.1477316
   4.82647115 14.35803776  2.83869333  5.78536237]
 [11.72333193  2.28525701  4.48035411 11.29872486 14.10963053  4.49070061
   6.06173032  5.24835195  3.32272461 11.12005469]
 [ 7.68423685  3.99209265 12.25140797  4.74391157  4.67770228  5.40024792
   5.31689533  8.63226702  7.63625936  2.4274878 ]
 [ 4.72217595  8.25441437  1.85343282  1.41186727  8.5013649   8.04308066
   3.56471625  7.66668404  3.79347479  1.17033352]
 [ 4.61970509  1.82880232  0.88155845  3.87855982  7.49446718  1.13451433
   3.69653461  1.60058913  2.96229578  5.89123061]
 [ 1.71064014  2.13236159  2.87428566  0.42743983  4.85508373  3.972235
   2.17049563  4.87642258  2.29807957  3.20458539]
 [ 1.10951331  3.52006522  2.73748642  1.39980831  4.49782435  6.00139265
   0.34929072  6.82585741  0.76526847  1.17624526]
 [ 0.56577927  0.63802769  4.85499764  1.49919907  3.40600949  1.94224115
   4.85430884  3.39018238  5.08047535  5.36034047]
 [ 4.08155314  4.50758583  9.84132717  0.35258316  1.4288174   1.73395701
   7.36540087  4.4413348   8.60583634  5.90988377]
 [ 7.15223448 10.7222427   4.64476979  0.81731108 11.09257472  8.63596863
   5.38289103  7.54390954  6.10500134  1.95186145]]

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

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
3Z = np.arange(1,15,dtype=np.uint32)
4R = stride_tricks.as_strided(Z,(11,4),(4,4))
5print(R)
[[ 1  2  3  4]
 [ 2  3  4  5]
 [ 3  4  5  6]
 [ 4  5  6  7]
 [ 5  6  7  8]
 [ 6  7  8  9]
 [ 7  8  9 10]
 [ 8  9 10 11]
 [ 9 10 11 12]
 [10 11 12 13]
 [11 12 13 14]]

82. Compute a matrix rank (★★★)

1# Author: Stefan van der Walt
2
3Z = np.random.uniform(0,1,(10,10))
4U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
5rank = np.sum(S > 1e-10)
6print(rank)
10

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

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

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

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

  [[0 2 0]
   [3 4 0]
   [2 4 3]]

  [[2 0 1]
   [4 0 0]
   [4 3 3]]

  [[0 1 1]
   [0 0 0]
   [3 3 2]]

  [[1 1 0]
   [0 0 1]
   [3 2 4]]

  [[1 0 4]
   [0 1 3]
   [2 4 1]]

  [[0 4 2]
   [1 3 4]
   [4 1 1]]

  [[4 2 2]
   [3 4 4]
   [1 1 3]]]


 [[[4 3 4]
   [4 2 4]
   [3 0 3]]

  [[3 4 0]
   [2 4 3]
   [0 3 0]]

  [[4 0 0]
   [4 3 3]
   [3 0 3]]

  [[0 0 0]
   [3 3 2]
   [0 3 4]]

  [[0 0 1]
   [3 2 4]
   [3 4 2]]

  [[0 1 3]
   [2 4 1]
   [4 2 2]]

  [[1 3 4]
   [4 1 1]
   [2 2 0]]

  [[3 4 4]
   [1 1 3]
   [2 0 2]]]


 [[[4 2 4]
   [3 0 3]
   [2 4 3]]

  [[2 4 3]
   [0 3 0]
   [4 3 0]]

  [[4 3 3]
   [3 0 3]
   [3 0 3]]

  [[3 3 2]
   [0 3 4]
   [0 3 3]]

  [[3 2 4]
   [3 4 2]
   [3 3 1]]

  [[2 4 1]
   [4 2 2]
   [3 1 2]]

  [[4 1 1]
   [2 2 0]
   [1 2 1]]

  [[1 1 3]
   [2 0 2]
   [2 1 3]]]


 [[[3 0 3]
   [2 4 3]
   [3 0 4]]

  [[0 3 0]
   [4 3 0]
   [0 4 1]]

  [[3 0 3]
   [3 0 3]
   [4 1 1]]

  [[0 3 4]
   [0 3 3]
   [1 1 4]]

  [[3 4 2]
   [3 3 1]
   [1 4 1]]

  [[4 2 2]
   [3 1 2]
   [4 1 3]]

  [[2 2 0]
   [1 2 1]
   [1 3 0]]

  [[2 0 2]
   [2 1 3]
   [3 0 1]]]


 [[[2 4 3]
   [3 0 4]
   [0 2 2]]

  [[4 3 0]
   [0 4 1]
   [2 2 0]]

  [[3 0 3]
   [4 1 1]
   [2 0 4]]

  [[0 3 3]
   [1 1 4]
   [0 4 3]]

  [[3 3 1]
   [1 4 1]
   [4 3 4]]

  [[3 1 2]
   [4 1 3]
   [3 4 0]]

  [[1 2 1]
   [1 3 0]
   [4 0 2]]

  [[2 1 3]
   [3 0 1]
   [0 2 1]]]


 [[[3 0 4]
   [0 2 2]
   [1 3 4]]

  [[0 4 1]
   [2 2 0]
   [3 4 1]]

  [[4 1 1]
   [2 0 4]
   [4 1 0]]

  [[1 1 4]
   [0 4 3]
   [1 0 1]]

  [[1 4 1]
   [4 3 4]
   [0 1 0]]

  [[4 1 3]
   [3 4 0]
   [1 0 1]]

  [[1 3 0]
   [4 0 2]
   [0 1 4]]

  [[3 0 1]
   [0 2 1]
   [1 4 1]]]


 [[[0 2 2]
   [1 3 4]
   [2 0 1]]

  [[2 2 0]
   [3 4 1]
   [0 1 2]]

  [[2 0 4]
   [4 1 0]
   [1 2 2]]

  [[0 4 3]
   [1 0 1]
   [2 2 0]]

  [[4 3 4]
   [0 1 0]
   [2 0 0]]

  [[3 4 0]
   [1 0 1]
   [0 0 4]]

  [[4 0 2]
   [0 1 4]
   [0 4 0]]

  [[0 2 1]
   [1 4 1]
   [4 0 1]]]


 [[[1 3 4]
   [2 0 1]
   [2 4 2]]

  [[3 4 1]
   [0 1 2]
   [4 2 3]]

  [[4 1 0]
   [1 2 2]
   [2 3 1]]

  [[1 0 1]
   [2 2 0]
   [3 1 4]]

  [[0 1 0]
   [2 0 0]
   [1 4 2]]

  [[1 0 1]
   [0 0 4]
   [4 2 0]]

  [[0 1 4]
   [0 4 0]
   [2 0 3]]

  [[1 4 1]
   [4 0 1]
   [0 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
 4class Symetric(np.ndarray):
 5    def __setitem__(self, index, value):
 6        i,j = index
 7        super(Symetric, self).__setitem__((i,j), value)
 8        super(Symetric, self).__setitem__((j,i), value)
 9
10def symetric(Z):
11    return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)
12
13S = symetric(np.random.randint(0,10,(5,5)))
14S[2,3] = 42
15print(S)
[[ 1 16  6  5  6]
 [16  5 13 16 12]
 [ 6 13  4 42  2]
 [ 5 16 42  2 13]
 [ 6 12  2 13  3]]

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
 3p, n = 10, 20
 4M = np.ones((p,n,n))
 5V = np.ones((p,n,1))
 6S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])
 7print(S)
 8
 9# It works, because:
10# M is (p,n,n)
11# V is (p,n,1)
12# Thus, summing over the paired axes 0 and 0 (of M and V independently),
13# and 2 and 1, to remain with a (n,1) vector.
[[200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]
 [200.]]

87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)

1# Author: Robert Kern
2
3Z = np.ones((16,16))
4k = 4
5S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),
6                                       np.arange(0, Z.shape[1], k), axis=1)
7print(S)
[[16. 16. 16. 16.]
 [16. 16. 16. 16.]
 [16. 16. 16. 16.]
 [16. 16. 16. 16.]]

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

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

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

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

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

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

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

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

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

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

TypeError                                 Traceback (most recent call last)

<ipython-input-92-4526b6c58168> in <module>()
      1 # Author: Ryan G.
      2 
----> 3 x = np.random.rand(5e7)
      4 
      5 get_ipython().run_line_magic('timeit', 'np.power(x,3)')


mtrand.pyx in mtrand.RandomState.rand()


mtrand.pyx in mtrand.RandomState.random_sample()


mtrand.pyx in mtrand.cont0_array()


TypeError: 'float' object cannot be interpreted as an integer

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
3A = np.random.randint(0,5,(8,3))
4B = np.random.randint(0,5,(2,2))
5
6C = (A[..., np.newaxis, np.newaxis] == B)
7rows = np.where(C.any((3,1)).all(1))[0]
8print(rows)
[]

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

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

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

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

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

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

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
 4A = np.random.uniform(0,1,10)
 5B = np.random.uniform(0,1,10)
 6
 7np.einsum('i->', A)       # np.sum(A)
 8np.einsum('i,i->i', A, B) # A * B
 9np.einsum('i,i', A, B)    # np.inner(A, B)
10np.einsum('i,j->ij', A, B)    # np.outer(A, B)
array([[0.06728041, 0.05397444, 0.0764441 , 0.22359054, 0.0836961 ,
        0.23600838, 0.01241854, 0.22915715, 0.07803804, 0.18796029],
       [0.17717534, 0.14213557, 0.20130688, 0.58880039, 0.22040419,
        0.62150136, 0.03270283, 0.60345942, 0.20550435, 0.49497216],
       [0.27189413, 0.21812194, 0.30892651, 0.90357594, 0.33823335,
        0.95375901, 0.05018592, 0.92607176, 0.31536797, 0.75958668],
       [0.06789412, 0.05446677, 0.07714139, 0.22563006, 0.08445954,
        0.23816117, 0.01253182, 0.23124745, 0.07874988, 0.1896748 ],
       [0.11831111, 0.09491285, 0.13442526, 0.39317904, 0.14717774,
        0.41501553, 0.02183773, 0.40296779, 0.13722817, 0.33052403],
       [0.23778707, 0.19076019, 0.27017402, 0.79022918, 0.29580454,
        0.83411717, 0.04389047, 0.80990307, 0.27580745, 0.66430229],
       [0.03397511, 0.02725589, 0.03860257, 0.11290827, 0.04226467,
        0.119179  , 0.00627109, 0.11571928, 0.03940748, 0.09491578],
       [0.08646755, 0.06936696, 0.09824455, 0.28735447, 0.10756469,
        0.30331365, 0.01596008, 0.29450857, 0.10029306, 0.24156312],
       [0.22622413, 0.18148404, 0.25703619, 0.75180248, 0.28142037,
        0.79355631, 0.0417562 , 0.77051968, 0.26239568, 0.63199907],
       [0.00686845, 0.00551008, 0.00780394, 0.02282566, 0.00854427,
        0.02409336, 0.00126777, 0.02339393, 0.00796666, 0.01918828]])

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

 1# Author: Bas Swinckels
 2
 3phi = np.arange(0, 10*np.pi, 0.1)
 4a = 1
 5x = a*phi*np.cos(phi)
 6y = a*phi*np.sin(phi)
 7
 8dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths
 9r = np.zeros_like(x)
10r[1:] = np.cumsum(dr)                # integrate path
11r_int = np.linspace(0, r.max(), 200) # regular spaced path
12x_int = np.interp(r_int, r, x)       # integrate path
13y_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
3X = np.asarray([[1.0, 0.0, 3.0, 8.0],
4                [2.0, 0.0, 1.0, 1.0],
5                [1.5, 2.5, 1.0, 0.0]])
6n = 4
7M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)
8M &= (X.sum(axis=-1) == n)
9print(X[M])
[[2. 0. 1. 1.]]

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
3X = np.random.randn(100) # random 1D array
4N = 1000 # number of bootstrap samples
5idx = np.random.randint(0, X.size, (N, X.size))
6means = X[idx].mean(axis=1)
7confint = np.percentile(means, [2.5, 97.5])
8print(confint)
[-0.30976616  0.02882422]