{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.4"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 100 numpy exercises\n\nThis 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.\n\n\nIf you find an error or think you've a better way to solve some of them, feel free to open an issue at ","metadata":{"_uuid":"7dac2651304bbdd274a99291c17f3be1e84c222b"}},{"cell_type":"markdown","source":"#### 1. Import the numpy package under the name `np` (★☆☆)","metadata":{"_uuid":"bf7265d79ded8d1b32c6ac6cf2ba89d6eba96461"}},{"cell_type":"code","source":"import numpy as np","metadata":{"_uuid":"1f42e0ab79d92a23b119e23ab8dda63393447466","collapsed":true,"jupyter":{"outputs_hidden":true}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 2. Print the numpy version and the configuration (★☆☆)","metadata":{"_uuid":"2a9c567c3500905ffd716f33d72f2ce455931c6b"}},{"cell_type":"code","source":"print(np.__version__)\nnp.show_config()","metadata":{"_uuid":"f92ca9022729c7247a92da557f1898051c1bf21d"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 3. Create a null vector of size 10 (★☆☆)","metadata":{"_uuid":"77978f9afb5f957440f180861ccb06c2f644c317"}},{"cell_type":"code","source":"Z = np.zeros(10)\nprint(Z)","metadata":{"_uuid":"beeb301d90b0fd6cb0f015969c969870bee981e8"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 4. How to find the memory size of any array (★☆☆)","metadata":{"_uuid":"9f2912dbc92ebcc2e86ac09930187d5d101552da"}},{"cell_type":"code","source":"Z = np.zeros((10,10))\nprint(\"%d bytes\" % (Z.size * Z.itemsize))","metadata":{"_uuid":"114a14936bde56cae519ed2f781f0b241251bdab"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)","metadata":{"_uuid":"61e755128e8631d194790854804d41362353f79d"}},{"cell_type":"code","source":"%run `python -c \"import numpy; numpy.info(numpy.add)\"`","metadata":{"_uuid":"aa773a98c7db3465372105c510a7627ae6dfee5d","collapsed":true,"jupyter":{"outputs_hidden":true}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)","metadata":{"_uuid":"c75ba6ea73f0a23f837c1553a0f564fbb8748557"}},{"cell_type":"code","source":"Z = np.zeros(10)\nZ[4] = 1\nprint(Z)","metadata":{"_uuid":"a916d1332f7e1d7499fd9de3bb422651711df025"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)","metadata":{"_uuid":"118478fd9f22dc99584c1517078f1cdd4a4b36fc"}},{"cell_type":"code","source":"Z = np.arange(10,50)\nprint(Z)","metadata":{"_uuid":"ac7cbc58129168a298298ae6d3a756a2a94c2a5d"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 8. Reverse a vector (first element becomes last) (★☆☆)","metadata":{"_uuid":"1c153cfc18b4c413b602d9fa073a4c049f1e703b"}},{"cell_type":"code","source":"Z = np.arange(50)\nZ = Z[::-1]\nprint(Z)","metadata":{"_uuid":"f1498235d2137116b1a7fabc6626dc8549235aba"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)","metadata":{"_uuid":"647011edcdd237ef4bfa0ec4ce3a108805bbd11f"}},{"cell_type":"code","source":"Z = np.arange(9).reshape(3,3)\nprint(Z)","metadata":{"_uuid":"d6bf86992dbc3539332876b2caf973bafdb9a790"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 10. Find indices of non-zero elements from \\[1,2,0,0,4,0\\] (★☆☆)","metadata":{"_uuid":"c7d5733bee779737b5ad4250b257d0a1423ffbff"}},{"cell_type":"code","source":"nz = np.nonzero([1,2,0,0,4,0])\nprint(nz)","metadata":{"_uuid":"e6e0544a4326eaf8f3ea6390a16422a9844d48fc"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 11. Create a 3x3 identity matrix (★☆☆)","metadata":{"_uuid":"ab5c1aaf0377ab923c6dbb7452671c181544734a"}},{"cell_type":"code","source":"Z = np.eye(3)\nprint(Z)","metadata":{"_uuid":"0e10bd7b228cff4c485d80142fa5afcea12eb0e1"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 12. Create a 3x3x3 array with random values (★☆☆)","metadata":{"_uuid":"9c3d53fd277d07937bc04838c4ca57a0aaaec498"}},{"cell_type":"code","source":"Z = np.random.random((3,3,3))\nprint(Z)","metadata":{"_uuid":"77840458ba47b330dd84bab7a119e85299856c57","collapsed":true,"jupyter":{"outputs_hidden":true}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)","metadata":{"_uuid":"886bef95cd1aa9af4133902b45b50127b5da54cb"}},{"cell_type":"code","source":"Z = np.random.random((10,10))\nZmin, Zmax = Z.min(), Z.max()\nprint(Zmin, Zmax)","metadata":{"_uuid":"a8c13dc011c6afb824c3a7031330b6bd1a77e497"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 14. Create a random vector of size 30 and find the mean value (★☆☆)","metadata":{"_uuid":"07db1e47dcff92113a6d4c696e92a5578b20d89f"}},{"cell_type":"code","source":"Z = np.random.random(30)\nm = Z.mean()\nprint(m)","metadata":{"_uuid":"a6533f70b28d583e6e1926a0e3e668b465d6ef6c"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)","metadata":{"_uuid":"2234dffb1dffc779d1d24f269da232a560848ad0"}},{"cell_type":"code","source":"Z = np.ones((10,10))\nZ[1:-1,1:-1] = 0\nprint(Z)","metadata":{"_uuid":"03bef7c11ab2593768ce88331a92c0c7cc10d463"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)","metadata":{"_uuid":"6e24eff853c1ead319eba0adf0efdf31a58c6944"}},{"cell_type":"code","source":"Z = np.ones((5,5))\nZ = np.pad(Z, pad_width=1, mode='constant', constant_values=0)\nprint(Z)","metadata":{"_uuid":"573dd1238aef49fed4a9cfeb645c09119a307916"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 17. What is the result of the following expression? (★☆☆)","metadata":{"_uuid":"1f657aee797f18a40aa7a5e98362719bc73ebdee"}},{"cell_type":"code","source":"print(0 * np.nan)\nprint(np.nan == np.nan)\nprint(np.inf > np.nan)\nprint(np.nan - np.nan)\nprint(np.nan in set([np.nan]))\nprint(0.3 == 3 * 0.1)","metadata":{"_uuid":"5bd51740ffe0b687da93acf403807897292ebbc5"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)","metadata":{"_uuid":"e22023622e0ec70b97ca378772dae42cff45d73c"}},{"cell_type":"code","source":"Z = np.diag(1+np.arange(4),k=-1)\nprint(Z)","metadata":{"_uuid":"f1aaa690119ec31eb516c96023250ff10f2800be"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)","metadata":{"_uuid":"2e1e85761e1eafa4cd8986a3aa28763f2b8197e2"}},{"cell_type":"code","source":"Z = np.zeros((8,8),dtype=int)\nZ[1::2,::2] = 1\nZ[::2,1::2] = 1\nprint(Z)","metadata":{"_uuid":"467504e8796a218a3faa0a787775d8aa577f4c32"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?","metadata":{"_uuid":"87e644b2696a16879dcf96b35b17a48db550cd04"}},{"cell_type":"code","source":"print(np.unravel_index(100,(6,7,8)))","metadata":{"_uuid":"eabdb2c5e23366c763f0cc39939ee68866c3f111"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)","metadata":{"_uuid":"13a635e9f2af055ba88eb102eeb4d8025570a93d"}},{"cell_type":"code","source":"Z = np.tile( np.array([[0,1],[1,0]]), (4,4))\nprint(Z)","metadata":{"_uuid":"ba1c748cbe8cf6a2cf8840b07c95cc9d17f1a596"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 22. Normalize a 5x5 random matrix (★☆☆)","metadata":{"_uuid":"87fb9e8995db8ee27d3c209c840f3f2c6acb9bc5"}},{"cell_type":"code","source":"Z = np.random.random((5,5))\nZ = (Z - np.mean (Z)) / (np.std (Z))\nprint(Z)","metadata":{"_uuid":"70b01b18cef5e31ffcc4c0219859e607e7a6d998"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)","metadata":{"_uuid":"a86da96f18b0eef155a85b49e36aaa51b2403a61"}},{"cell_type":"code","source":"color = np.dtype([(\"r\", np.ubyte, 1),\n (\"g\", np.ubyte, 1),\n (\"b\", np.ubyte, 1),\n (\"a\", np.ubyte, 1)])","metadata":{"_uuid":"30ac92f0e3667aacb75ec6fba40c34bcfec9529e","collapsed":true,"jupyter":{"outputs_hidden":true}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)","metadata":{"_uuid":"659926bf5bf80842361a658fd0f84bf24084fbf3"}},{"cell_type":"code","source":"Z = np.dot(np.ones((5,3)), np.ones((3,2)))\nprint(Z)\n\n# Alternative solution, in Python 3.5 and above\nZ = np.ones((5,3)) @ np.ones((3,2))","metadata":{"_uuid":"8be73ba1bd9778d487ac20ef5658c7b8e57c3d67"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)","metadata":{"_uuid":"0a65567844ac53a18dbb387a8694da2b1c78294a"}},{"cell_type":"code","source":"# Author: Evgeni Burovski\n\nZ = np.arange(11)\nZ[(3 < Z) & (Z <= 8)] *= -1\nprint(Z)","metadata":{"_uuid":"d48512adb16f06371f651dd8dc1ae9ea1c3586b1"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 26. What is the output of the following script? (★☆☆)","metadata":{"_uuid":"dad4e194cbf30833bbc7dba6714e300239088610"}},{"cell_type":"code","source":"# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))","metadata":{"_uuid":"094e225f24cf70ad8c7caeb1dcbd6788e5af562a"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)","metadata":{"_uuid":"c13814936adf93d11212e3e85e67a37e48b1fd72"}},{"cell_type":"code","source":"Z**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZZ","metadata":{"_uuid":"2d41e8fd1c2a4970ea55fcf50524a01e083d7f01"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 28. What are the result of the following expressions?","metadata":{"_uuid":"87cfa6cec4f5f3efa4d92b7d01be3e15e92eb8d9"}},{"cell_type":"code","source":"print(np.array(0) / np.array(0))\nprint(np.array(0) // np.array(0))\nprint(np.array([np.nan]).astype(int).astype(float))","metadata":{"_uuid":"8b9ea83b2b3a14de49b957a490ded427b2fdf473"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 29. How to round away from zero a float array ? (★☆☆)","metadata":{"_uuid":"748fc33413222da461b2aac2a9fcabff3e18e057"}},{"cell_type":"code","source":"# Author: Charles R Harris\n\nZ = np.random.uniform(-10,+10,10)\nprint (np.copysign(np.ceil(np.abs(Z)), Z))","metadata":{"_uuid":"b9e1b1bef8f15c72cc7ce5e2ce14def4a98ed41c"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 30. How to find common values between two arrays? (★☆☆)","metadata":{"_uuid":"e49ca0d2249b4a5cf25b264e42c6feb3057889ed"}},{"cell_type":"code","source":"Z1 = np.random.randint(0,10,10)\nZ2 = np.random.randint(0,10,10)\nprint(np.intersect1d(Z1,Z2))","metadata":{"_uuid":"b7a1b2802e4c4a2ac5baf737e2065c55bef226b6"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)","metadata":{"_uuid":"18843482db38cbb4ca8de77cb7c7e787acd5fa20"}},{"cell_type":"code","source":"# Suicide mode on\ndefaults = np.seterr(all=\"ignore\")\nZ = np.ones(1) / 0\n\n# Back to sanity\n_ = np.seterr(**defaults)\n\nAn equivalent way, with a context manager:\n\nwith np.errstate(divide='ignore'):\n Z = np.ones(1) / 0","metadata":{"_uuid":"c71bd60875133429395886e0b8e3bfa343d40b42"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 32. Is the following expressions true? (★☆☆)","metadata":{"_uuid":"dcb0cd567860239870f01fd07f5afa59961b6b89"}},{"cell_type":"code","source":"np.sqrt(-1) == np.emath.sqrt(-1)","metadata":{"_uuid":"e494de30ea8f90e4263b3c3de452105d762a2996"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)","metadata":{"_uuid":"68d59ad2323d4ede5a110e8d9650aab01eb5174d"}},{"cell_type":"code","source":"yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')\ntoday = np.datetime64('today', 'D')\ntomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')","metadata":{"_uuid":"1525d48cd65e2639eeb08299708319a07e6b80de","collapsed":true,"jupyter":{"outputs_hidden":true}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)","metadata":{"_uuid":"d8e6dcb1cf0ae2d7c4fc08a657a186df0f4f171f"}},{"cell_type":"code","source":"Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')\nprint(Z)","metadata":{"_uuid":"f5f3000257839f44772b54320bd185b8046ed0e2"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 35. How to compute ((A+B)\\*(-A/2)) in place (without copy)? (★★☆)","metadata":{"_uuid":"9e2512ad8b29d3599cababc7009febce91929869"}},{"cell_type":"code","source":"A = np.ones(3)*1\nB = np.ones(3)*2\nC = np.ones(3)*3\nnp.add(A,B,out=B)\nnp.divide(A,2,out=A)\nnp.negative(A,out=A)\nnp.multiply(A,B,out=A)","metadata":{"_uuid":"4fb34450b8dfabe74d9e411ec45c717e15a0efcd"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 36. Extract the integer part of a random array using 5 different methods (★★☆)","metadata":{"_uuid":"861564e1209df602ba9acf76b21764166d941f64"}},{"cell_type":"code","source":"Z = np.random.uniform(0,10,10)\n\nprint (Z - Z%1)\nprint (np.floor(Z))\nprint (np.ceil(Z)-1)\nprint (Z.astype(int))\nprint (np.trunc(Z))","metadata":{"_uuid":"26071c39ddc28c65fe06329b480504455890609e"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)","metadata":{"_uuid":"1acff22fb998865b58d5a9b37b0a5ce5b7f13387"}},{"cell_type":"code","source":"Z = np.zeros((5,5))\nZ += np.arange(5)\nprint(Z)","metadata":{"_uuid":"728c78dc7d9477e3300f58d589fbbc888df3cecb"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)","metadata":{"_uuid":"dd54ec03c8ce814c994611575b49cd2e14b4071a"}},{"cell_type":"code","source":"def generate():\n for x in range(10):\n yield x\nZ = np.fromiter(generate(),dtype=float,count=-1)\nprint(Z)","metadata":{"_uuid":"229a68e06163a294e63f0b377aa697aa8c925cb2"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)","metadata":{"_uuid":"c52ceff787ef50f22325107cb5f5b1bfac61858f"}},{"cell_type":"code","source":"Z = np.linspace(0,1,11,endpoint=False)[1:]\nprint(Z)","metadata":{"_uuid":"bcdb9a3b3a6a47768f53ea8e25b70070566c87eb"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 40. Create a random vector of size 10 and sort it (★★☆)","metadata":{"_uuid":"34f5d6e2e269678714f1e5aafec8a92d6411ecd3"}},{"cell_type":"code","source":"Z = np.random.random(10)\nZ.sort()\nprint(Z)","metadata":{"_uuid":"650bd640404dd8cfdbeb0d91b8fc5ea844ee60a8"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 41. How to sum a small array faster than np.sum? (★★☆)","metadata":{"_uuid":"83c5fbdf8c61a57380aa9deeb60fb1546c5560bc"}},{"cell_type":"code","source":"# Author: Evgeni Burovski\n\nZ = np.arange(10)\nnp.add.reduce(Z)","metadata":{"_uuid":"1c694d4f7a152005de0201d7459cca0fb9daf820"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 42. Consider two random array A and B, check if they are equal (★★☆)","metadata":{"_uuid":"0502011982ec9de8f998bdcc76ff2d00dc9bad6e"}},{"cell_type":"code","source":"A = np.random.randint(0,2,5)\nB = np.random.randint(0,2,5)\n\n# Assuming identical shape of the arrays and a tolerance for the comparison of values\nequal = np.allclose(A,B)\nprint(equal)\n\n# Checking both the shape and the element values, no tolerance (values have to be exactly equal)\nequal = np.array_equal(A,B)\nprint(equal)","metadata":{"_uuid":"bc542c3112954260eac0bcf08bc8b0ae2ce0ae33"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 43. Make an array immutable (read-only) (★★☆)","metadata":{"_uuid":"100623c44dc702d6ac2ac5d35b4e5173c906f317"}},{"cell_type":"code","source":"Z = np.zeros(10)\nZ.flags.writeable = False\nZ[0] = 1","metadata":{"_uuid":"14189438d83341e3e1f92c6a2ced78eefe330569"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)","metadata":{"_uuid":"acb91faea0d29424787d28d2b532530712d96843"}},{"cell_type":"code","source":"Z = np.random.random((10,2))\nX,Y = Z[:,0], Z[:,1]\nR = np.sqrt(X**2+Y**2)\nT = np.arctan2(Y,X)\nprint(R)\nprint(T)","metadata":{"_uuid":"cc45f36860f02c3fcedb45f0c5358e6d432334d7"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)","metadata":{"_uuid":"353f854c6c99f2889b0d31cc69bc1fd7fccd0fe1"}},{"cell_type":"code","source":"Z = np.random.random(10)\nZ[Z.argmax()] = 0\nprint(Z)","metadata":{"_uuid":"fd9c6de99887f58497e8880f38b8aab24beaef6a"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 46. Create a structured array with `x` and `y` coordinates covering the \\[0,1\\]x\\[0,1\\] area (★★☆)","metadata":{"_uuid":"f7790f5d373c9f35e4407da026b1f432678e6a54"}},{"cell_type":"code","source":"Z = np.zeros((5,5), [('x',float),('y',float)])\nZ['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),\n np.linspace(0,1,5))\nprint(Z)","metadata":{"_uuid":"d41b7ebb14c22e1a447c4fed771bcc806a2e30b1"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))","metadata":{"_uuid":"1300814d19e6012622274d6a0a7b5551159278dc"}},{"cell_type":"code","source":"# Author: Evgeni Burovski\n\nX = np.arange(8)\nY = X + 0.5\nC = 1.0 / np.subtract.outer(X, Y)\nprint(np.linalg.det(C))","metadata":{"_uuid":"991ae1730e3cfac3214f49ffa0734512d4136779"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)","metadata":{"_uuid":"879952e7f6a37f63e8ebadf4baa516325eeb60c6"}},{"cell_type":"code","source":"for dtype in [np.int8, np.int32, np.int64]:\n print(np.iinfo(dtype).min)\n print(np.iinfo(dtype).max)\nfor dtype in [np.float32, np.float64]:\n print(np.finfo(dtype).min)\n print(np.finfo(dtype).max)\n print(np.finfo(dtype).eps)","metadata":{"_uuid":"c0582da4b3a82183e3230a0249e9a07bb9329698"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 49. How to print all the values of an array? (★★☆)","metadata":{"_uuid":"7ce0b16c0951d51c8a9755e83432bcb5faa7b542"}},{"cell_type":"code","source":"np.set_printoptions(threshold=np.nan)\nZ = np.zeros((16,16))\nprint(Z)","metadata":{"_uuid":"b79dd172d33c2f817244df8ebafda90e1974ea26"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)","metadata":{"_uuid":"3cd7d90b37471536a03b27117c01d82a1ed1439c"}},{"cell_type":"code","source":"Z = np.arange(100)\nv = np.random.uniform(0,100)\nindex = (np.abs(Z-v)).argmin()\nprint(Z[index])","metadata":{"_uuid":"2d0087af5d396d4b823122485c006f0e4a8f5b86"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)","metadata":{"_uuid":"6282f6e53b61d3d121c0a4be1bb3441da1069e37"}},{"cell_type":"code","source":"Z = np.zeros(10, [ ('position', [ ('x', float, 1),\n ('y', float, 1)]),\n ('color', [ ('r', float, 1),\n ('g', float, 1),\n ('b', float, 1)])])\nprint(Z)","metadata":{"_uuid":"3a84a0c89222c2e959c7a618c2d5f70f1b1b3066"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)","metadata":{"_uuid":"d516168bf762ce6077e2d6aff43d1e075e6bb252"}},{"cell_type":"code","source":"Z = np.random.random((10,2))\nX,Y = np.atleast_2d(Z[:,0], Z[:,1])\nD = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)\nprint(D)\n\n# Much faster with scipy\nimport scipy\n# Thanks Gavin Heverly-Coulson (#issue 1)\nimport scipy.spatial\n\nZ = np.random.random((10,2))\nD = scipy.spatial.distance.cdist(Z,Z)\nprint(D)","metadata":{"_uuid":"65d11532bfd393269790b8209036a862545f5154"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 53. How to convert a float (32 bits) array into an integer (32 bits) in place?","metadata":{"_uuid":"35b4e9307a72301c43b077924e4674cdee69fdf0"}},{"cell_type":"code","source":"Z = np.arange(10, dtype=np.float32)\nZ = Z.astype(np.int32, copy=False)\nprint(Z)","metadata":{"_uuid":"c67695d2efff4f63dbe4037694504a84deb8d4b9"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 54. How to read the following file? (★★☆)","metadata":{"_uuid":"ba624a09e6c7ad2469893f0803914f9df40b6e43"}},{"cell_type":"code","source":"from io import StringIO\n\n# Fake file \ns = StringIO(\"\"\"1, 2, 3, 4, 5\\n\n 6, , , 7, 8\\n\n , , 9,10,11\\n\"\"\")\nZ = np.genfromtxt(s, delimiter=\",\", dtype=np.int)\nprint(Z)","metadata":{"_uuid":"18545a5b5bde85eb8b664df655672a35a88e63b1"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)","metadata":{"_uuid":"2069af8a433b9e7ed0adba61834ee1c08a691e86"}},{"cell_type":"code","source":"Z = np.arange(9).reshape(3,3)\nfor index, value in np.ndenumerate(Z):\n print(index, value)\nfor index in np.ndindex(Z.shape):\n print(index, Z[index])","metadata":{"_uuid":"336bd26b33356fb424875e33319f8bd857b29f30"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 56. Generate a generic 2D Gaussian-like array (★★☆)","metadata":{"_uuid":"93ffc8b3b84a62c05657bebcea6a1f825017907f"}},{"cell_type":"code","source":"X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\nD = np.sqrt(X*X+Y*Y)\nsigma, mu = 1.0, 0.0\nG = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )\nprint(G)","metadata":{"_uuid":"8c14b899fb4ecb85fbbfea299f36d42f567fce25"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 57. How to randomly place p elements in a 2D array? (★★☆)","metadata":{"_uuid":"389113b4e22ac2f5454686a38fa9f4e2500e4c52"}},{"cell_type":"code","source":"# Author: Divakar\n\nn = 10\np = 3\nZ = np.zeros((n,n))\nnp.put(Z, np.random.choice(range(n*n), p, replace=False),1)\nprint(Z)","metadata":{"_uuid":"442c3c5664c0d9dbbe7149a0924e47c4a9699097"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 58. Subtract the mean of each row of a matrix (★★☆)","metadata":{"_uuid":"ad23d8b28a5016197192b4a6ecdfa61d3c54f49f"}},{"cell_type":"code","source":"# Author: Warren Weckesser\n\nX = np.random.rand(5, 10)\n\n# Recent versions of numpy\nY = X - X.mean(axis=1, keepdims=True)\n\n# Older versions of numpy\nY = X - X.mean(axis=1).reshape(-1, 1)\n\nprint(Y)","metadata":{"_uuid":"62937a93af1f4bd2ee201a0a28d92ad2e39aeadf"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 59. How to sort an array by the nth column? (★★☆)","metadata":{"_uuid":"6dfaee28f6ffc182b31d95b2dd7db135b3cda134"}},{"cell_type":"code","source":"# Author: Steve Tjoa\n\nZ = np.random.randint(0,10,(3,3))\nprint(Z)\nprint(Z[Z[:,1].argsort()])","metadata":{"_uuid":"6d6526eff2206d6766e34a8a9d4aa45222304ecc"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 60. How to tell if a given 2D array has null columns? (★★☆)","metadata":{"_uuid":"26c24e107a164a8a931e1458db472aeabc0dd9d1"}},{"cell_type":"code","source":"# Author: Warren Weckesser\n\nZ = np.random.randint(0,3,(3,10))\nprint((~Z.any(axis=0)).any())","metadata":{"_uuid":"dd0d10eb40f387704fb2d5873460e2ff8d40a6a2"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 61. Find the nearest value from a given value in an array (★★☆)","metadata":{"_uuid":"c446326eba80f10ee44e69c38975a02b76272c66"}},{"cell_type":"code","source":"Z = np.random.uniform(0,1,10)\nz = 0.5\nm = Z.flat[np.abs(Z - z).argmin()]\nprint(m)","metadata":{"_uuid":"475de3550f77c7407940a0b31eeb5016286445c4"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)","metadata":{"_uuid":"ed78b6480e33d62936d0454ef9757390456a37e8"}},{"cell_type":"code","source":"A = np.arange(3).reshape(3,1)\nB = np.arange(3).reshape(1,3)\nit = np.nditer([A,B,None])\nfor x,y,z in it: z[...] = x + y\nprint(it.operands[2])","metadata":{"_uuid":"59b473c6731410e9a83cbf30b56fc6463c4ee8a4"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 63. Create an array class that has a name attribute (★★☆)","metadata":{"_uuid":"7c4a7f4c7f71603b7803cb77e1c8dc4556378f4b"}},{"cell_type":"code","source":"class NamedArray(np.ndarray):\n def __new__(cls, array, name=\"no name\"):\n obj = np.asarray(array).view(cls)\n obj.name = name\n return obj\n def __array_finalize__(self, obj):\n if obj is None: return\n self.info = getattr(obj, 'name', \"no name\")\n\nZ = NamedArray(np.arange(10), \"range_10\")\nprint (Z.name)","metadata":{"_uuid":"561bba582d49b158a3d3f9129d7874d8fe74644a"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)","metadata":{"_uuid":"28ced8d1105155575199e1e57e16ab27ba7dcb3c"}},{"cell_type":"code","source":"# Author: Brett Olsen\n\nZ = np.ones(10)\nI = np.random.randint(0,len(Z),20)\nZ += np.bincount(I, minlength=len(Z))\nprint(Z)\n\n# Another solution\n# Author: Bartosz Telenczuk\nnp.add.at(Z, I, 1)\nprint(Z)","metadata":{"_uuid":"f084a985aaaa6582f0fe1d3a24db309414ee85ed"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)","metadata":{"_uuid":"3c1d4443ce35bca0ec477f22957adc49b3da9071"}},{"cell_type":"code","source":"# Author: Alan G Isaac\n\nX = [1,2,3,4,5,6]\nI = [1,3,9,3,4,1]\nF = np.bincount(I,X)\nprint(F)","metadata":{"_uuid":"6397f06d610a9363b0907cec7fd545c22d34879c"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★★)","metadata":{"_uuid":"3ee7aa17d1e2574ff7c9467ce117a84bf1457a90"}},{"cell_type":"code","source":"# Author: Nadav Horesh\n\nw,h = 16,16\nI = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)\n#Note that we should compute 256*256 first. \n#Otherwise numpy will only promote F.dtype to 'uint16' and overfolw will occur\nF = I[...,0]*(256*256) + I[...,1]*256 +I[...,2]\nn = len(np.unique(F))\nprint(n)","metadata":{"_uuid":"c29b77b23a40a737a9710d16ba88c1d32274a905"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)","metadata":{"_uuid":"1f437c758e09b1d20cdb7db2d58806768c3914e1"}},{"cell_type":"code","source":"A = np.random.randint(0,10,(3,4,3,4))\n# solution by passing a tuple of axes (introduced in numpy 1.7.0)\nsum = A.sum(axis=(-2,-1))\nprint(sum)\n# solution by flattening the last two dimensions into one\n# (useful for functions that don't accept tuples for axis argument)\nsum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\nprint(sum)","metadata":{"_uuid":"acbe18b60c84054f6744757f00d565de06c70084"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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? (★★★)","metadata":{"_uuid":"69e45dc9ae67c5a964c1f44e7d434c12356e55f6"}},{"cell_type":"code","source":"# Author: Jaime Fernández del Río\n\nD = np.random.uniform(0,1,100)\nS = np.random.randint(0,10,100)\nD_sums = np.bincount(S, weights=D)\nD_counts = np.bincount(S)\nD_means = D_sums / D_counts\nprint(D_means)\n\n# Pandas solution as a reference due to more intuitive code\nimport pandas as pd\nprint(pd.Series(D).groupby(S).mean())","metadata":{"_uuid":"a9fe735c39c47e3c43a2b475c3ca3ecf72aa0985"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 69. How to get the diagonal of a dot product? (★★★)","metadata":{"_uuid":"620cc111a526a41f264e47d9738fb2d27ef1aa6e"}},{"cell_type":"code","source":"# Author: Mathieu Blondel\n\nA = np.random.uniform(0,1,(5,5))\nB = np.random.uniform(0,1,(5,5))\n\n# Slow version \nnp.diag(np.dot(A, B))\n\n# Fast version\nnp.sum(A * B.T, axis=1)\n\n# Faster version\nnp.einsum(\"ij,ji->i\", A, B)","metadata":{"_uuid":"752296a67bbe85f6b35a51255964822fd4373a36"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 70. Consider the vector \\[1, 2, 3, 4, 5\\], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)","metadata":{"_uuid":"e117871c83cf8f95effaeaf57c8e39d342173ac8"}},{"cell_type":"code","source":"# Author: Warren Weckesser\n\nZ = np.array([1,2,3,4,5])\nnz = 3\nZ0 = np.zeros(len(Z) + (len(Z)-1)*(nz))\nZ0[::nz+1] = Z\nprint(Z0)","metadata":{"_uuid":"6ca8fdad8b10470dc10098a00b5a82df503b9f30"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)","metadata":{"_uuid":"967288203450de09d5761904c7911e16c842b6b3"}},{"cell_type":"code","source":"A = np.ones((5,5,3))\nB = 2*np.ones((5,5))\nprint(A * B[:,:,None])","metadata":{"_uuid":"ce08e9ef2d47e6b39da8c3587ae27223aaeebdff","collapsed":true,"jupyter":{"outputs_hidden":true}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 72. How to swap two rows of an array? (★★★)","metadata":{"_uuid":"899841bbc67e2a7e0f51536f3191625078f29864"}},{"cell_type":"code","source":"# Author: Eelco Hoogendoorn\n\nA = np.arange(25).reshape(5,5)\nA[[0,1]] = A[[1,0]]\nprint(A)","metadata":{"_uuid":"c1e1056d07c1b9be34aa5c71beb522b57b450bc3"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)","metadata":{"_uuid":"27b3d2e02f5c0a32071d3efbf9528a5a0a54d763"}},{"cell_type":"code","source":"# Author: Nicolas P. Rougier\n\nfaces = np.random.randint(0,100,(10,3))\nF = np.roll(faces.repeat(2,axis=1),-1,axis=1)\nF = F.reshape(len(F)*3,2)\nF = np.sort(F,axis=1)\nG = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )\nG = np.unique(G)\nprint(G)","metadata":{"_uuid":"d585765a886d99e53361320c28a1e6aa5e0e4ebc"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 74. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)","metadata":{"_uuid":"4822e0e421b959ecd054474216e08fcba9aaced8"}},{"cell_type":"code","source":"# Author: Jaime Fernández del Río\n\nC = np.bincount([1,1,2,3,4,4,6])\nA = np.repeat(np.arange(len(C)), C)\nprint(A)","metadata":{"_uuid":"fea19dbeb6be018c63a67319fc6c6abe9d3b6dfb"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 75. How to compute averages using a sliding window over an array? (★★★)","metadata":{"_uuid":"db98ac94341682cad0c85dc68c7dba1572346778"}},{"cell_type":"code","source":"# Author: Jaime Fernández del Río\n\ndef moving_average(a, n=3) :\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\nZ = np.arange(20)\nprint(moving_average(Z, n=3))","metadata":{"_uuid":"aaa1f7e514e17e55758647e682d746de91fe0c52"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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\\]) (★★★)","metadata":{"_uuid":"794378d0e03ed3462a6f87827ffae487496cf85d"}},{"cell_type":"code","source":"# Author: Joe Kington / Erik Rigtorp\nfrom numpy.lib import stride_tricks\n\ndef rolling(a, window):\n shape = (a.size - window + 1, window)\n strides = (a.itemsize, a.itemsize)\n return stride_tricks.as_strided(a, shape=shape, strides=strides)\nZ = rolling(np.arange(10), 3)\nprint(Z)","metadata":{"_uuid":"9ef5a36a4d0ce67c1ed4327e983105fc5ba56fb3"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)","metadata":{"_uuid":"f5349e34f831b12ac2f7b75bc67a065ba32d71df"}},{"cell_type":"code","source":"# Author: Nathaniel J. Smith\n\nZ = np.random.randint(0,2,100)\nnp.logical_not(Z, out=Z)\n\nZ = np.random.uniform(-1.0,1.0,100)\nnp.negative(Z, out=Z)","metadata":{"_uuid":"f0a9b5c8c0b3667c6445ef1f9261246571f3d0e6"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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\\])? (★★★)","metadata":{"_uuid":"ce309f54e1032b505c9fced97839bf257bc2cf64"}},{"cell_type":"code","source":"def distance(P0, P1, p):\n T = P1 - P0\n L = (T**2).sum(axis=1)\n U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L\n U = U.reshape(len(U),1)\n D = P0 + U*T - p\n return np.sqrt((D**2).sum(axis=1))\n\nP0 = np.random.uniform(-10,10,(10,2))\nP1 = np.random.uniform(-10,10,(10,2))\np = np.random.uniform(-10,10,( 1,2))\nprint(distance(P0, P1, p))","metadata":{"_uuid":"b5d3bc01c0d08e0f1d7e5c08d737b7bdf138b19c"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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\\])? (★★★)","metadata":{"_uuid":"df3a094eb31c73f48bfb72132dadbe47a69e8bb4"}},{"cell_type":"code","source":"# Author: Italmassov Kuanysh\n\n# based on distance function from previous question\nP0 = np.random.uniform(-10, 10, (10,2))\nP1 = np.random.uniform(-10,10,(10,2))\np = np.random.uniform(-10, 10, (10,2))\nprint(np.array([distance(P0,P1,p_i) for p_i in p]))","metadata":{"_uuid":"1fdccdc0a96f92195c8b57bbc821708d86fba2be"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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) (★★★)","metadata":{"_uuid":"4cf8d4a09224f87c8df4de7af1fb6bd79e255769"}},{"cell_type":"code","source":"# Author: Nicolas Rougier\n\nZ = np.random.randint(0,10,(10,10))\nshape = (5,5)\nfill = 0\nposition = (1,1)\n\nR = np.ones(shape, dtype=Z.dtype)*fill\nP = np.array(list(position)).astype(int)\nRs = np.array(list(R.shape)).astype(int)\nZs = np.array(list(Z.shape)).astype(int)\n\nR_start = np.zeros((len(shape),)).astype(int)\nR_stop = np.array(list(shape)).astype(int)\nZ_start = (P-Rs//2)\nZ_stop = (P+Rs//2)+Rs%2\n\nR_start = (R_start - np.minimum(Z_start,0)).tolist()\nZ_start = (np.maximum(Z_start,0)).tolist()\nR_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()\nZ_stop = (np.minimum(Z_stop,Zs)).tolist()\n\nr = [slice(start,stop) for start,stop in zip(R_start,R_stop)]\nz = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]\nR[r] = Z[z]\nprint(Z)\nprint(R)","metadata":{"_uuid":"bd0f84fa830cff3baa5923ed8766475674375685"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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\\]\\]? (★★★)","metadata":{"_uuid":"8c82f8a6f87f80e600419bc6e3728b21dbc4b8ff"}},{"cell_type":"code","source":"# Author: Stefan van der Walt\n\nZ = np.arange(1,15,dtype=np.uint32)\nR = stride_tricks.as_strided(Z,(11,4),(4,4))\nprint(R)","metadata":{"_uuid":"bef941cec7f009e83a39913705597ef1085a25b3"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 82. Compute a matrix rank (★★★)","metadata":{"_uuid":"657e96419a48dfb4bc697876935cef0e6cdcb8f5"}},{"cell_type":"code","source":"# Author: Stefan van der Walt\n\nZ = np.random.uniform(0,1,(10,10))\nU, S, V = np.linalg.svd(Z) # Singular Value Decomposition\nrank = np.sum(S > 1e-10)\nprint(rank)","metadata":{"_uuid":"10403fe400f5d3cdeb5725cb628830230c754ec1"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 83. How to find the most frequent value in an array?","metadata":{"_uuid":"24b86507600d4f283f09b3117a0b9266446e5b98"}},{"cell_type":"code","source":"Z = np.random.randint(0,10,50)\nprint(np.bincount(Z).argmax())","metadata":{"_uuid":"bc112b94dc08691f315afb878bdd2c52cbb4c3bc"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)","metadata":{"_uuid":"62f38d5b2a9486d69d708d91a2ff76c52b5e409e"}},{"cell_type":"code","source":"# Author: Chris Barker\n\nZ = np.random.randint(0,5,(10,10))\nn = 3\ni = 1 + (Z.shape[0]-3)\nj = 1 + (Z.shape[1]-3)\nC = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)\nprint(C)","metadata":{"_uuid":"b21371cfb99568a01218ce485aca3089f38d45cf"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 85. Create a 2D array subclass such that Z\\[i,j\\] == Z\\[j,i\\] (★★★)","metadata":{"_uuid":"356cb226b8732db0b4956dcbb10146f370e5b21a"}},{"cell_type":"code","source":"# Author: Eric O. Lebigot\n# Note: only works for 2d array and value setting using indices\n\nclass Symetric(np.ndarray):\n def __setitem__(self, index, value):\n i,j = index\n super(Symetric, self).__setitem__((i,j), value)\n super(Symetric, self).__setitem__((j,i), value)\n\ndef symetric(Z):\n return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)\n\nS = symetric(np.random.randint(0,10,(5,5)))\nS[2,3] = 42\nprint(S)","metadata":{"_uuid":"50cab105c14392c68f791edcb3d65920bc84c07d"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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)) (★★★)","metadata":{"_uuid":"eee96b7539939d2440942d090dbb3aa1b740536f"}},{"cell_type":"code","source":"# Author: Stefan van der Walt\n\np, n = 10, 20\nM = np.ones((p,n,n))\nV = np.ones((p,n,1))\nS = np.tensordot(M, V, axes=[[0, 2], [0, 1]])\nprint(S)\n\n# It works, because:\n# M is (p,n,n)\n# V is (p,n,1)\n# Thus, summing over the paired axes 0 and 0 (of M and V independently),\n# and 2 and 1, to remain with a (n,1) vector.","metadata":{"_uuid":"40736a29c5fb6424104130976aa4c27cc8ed77df"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)","metadata":{"_uuid":"a818718ccd3bec10bb97bd7ceb01d269df14f0b9"}},{"cell_type":"code","source":"# Author: Robert Kern\n\nZ = np.ones((16,16))\nk = 4\nS = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),\n np.arange(0, Z.shape[1], k), axis=1)\nprint(S)","metadata":{"_uuid":"b92047bfcc3cd8ea2d2c33f42c2cf34e0284ed1e"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 88. How to implement the Game of Life using numpy arrays? (★★★)","metadata":{"_uuid":"5efdc16efb03117e516f8b10aa9413a5abc70e02"}},{"cell_type":"code","source":"# Author: Nicolas Rougier\n\ndef iterate(Z):\n # Count neighbours\n N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +\n Z[1:-1,0:-2] + Z[1:-1,2:] +\n Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])\n\n # Apply rules\n birth = (N==3) & (Z[1:-1,1:-1]==0)\n survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)\n Z[...] = 0\n Z[1:-1,1:-1][birth | survive] = 1\n return Z\n\nZ = np.random.randint(0,2,(50,50))\nfor i in range(100): Z = iterate(Z)\nprint(Z)","metadata":{"_uuid":"e6bdac77a289d19582779ef6853c1102433b7b8e"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 89. How to get the n largest values of an array (★★★)","metadata":{"_uuid":"976eba1abb40955e6bf05a5847ec1bf8591fab05"}},{"cell_type":"code","source":"Z = np.arange(10000)\nnp.random.shuffle(Z)\nn = 5\n\n# Slow\nprint (Z[np.argsort(Z)[-n:]])\n\n# Fast\nprint (Z[np.argpartition(-Z,n)[:n]])","metadata":{"_uuid":"130ddce34dd70f334a1e0bd51b733a4b84a9bfc1"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)","metadata":{"_uuid":"ffe9e29aa6750ab693ef37ca60c461a82a761dd9"}},{"cell_type":"code","source":"# Author: Stefan Van der Walt\n\ndef cartesian(arrays):\n arrays = [np.asarray(a) for a in arrays]\n shape = (len(x) for x in arrays)\n\n ix = np.indices(shape, dtype=int)\n ix = ix.reshape(len(arrays), -1).T\n\n for n, arr in enumerate(arrays):\n ix[:, n] = arrays[n][ix[:, n]]\n\n return ix\n\nprint (cartesian(([1, 2, 3], [4, 5], [6, 7])))","metadata":{"scrolled":true,"_uuid":"cb67f935dd1f8f683ba5f06c9cf2a31d53ace2ef"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 91. How to create a record array from a regular array? (★★★)","metadata":{"_uuid":"16034f8e04d44923f487cd2a734692578b585dfc"}},{"cell_type":"code","source":"Z = np.array([(\"Hello\", 2.5, 3),\n (\"World\", 3.6, 2)])\nR = np.core.records.fromarrays(Z.T, \n names='col1, col2, col3',\n formats = 'S8, f8, i8')\nprint(R)","metadata":{"_uuid":"a243156ca67b3a776cf9f4471a3f35e9399fa868"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)","metadata":{"_uuid":"4af186d08ff5a394f0bd3df61c08924180664242"}},{"cell_type":"code","source":"# Author: Ryan G.\n\nx = np.random.rand(5e7)\n\n%timeit np.power(x,3)\n%timeit x*x*x\n%timeit np.einsum('i,i,i->i',x,x,x)","metadata":{"_uuid":"0d9e52e4417bf25096d540a15624f30ff3517c55"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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? (★★★)","metadata":{"_uuid":"31e96d464715e1711345f674f79cb64703d39f69"}},{"cell_type":"code","source":"# Author: Gabe Schwartz\n\nA = np.random.randint(0,5,(8,3))\nB = np.random.randint(0,5,(2,2))\n\nC = (A[..., np.newaxis, np.newaxis] == B)\nrows = np.where(C.any((3,1)).all(1))[0]\nprint(rows)","metadata":{"_uuid":"6f54c8d1c80000fd49423927dc9cbf2cd820acd9"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. \\[2,2,3\\]) (★★★)","metadata":{"_uuid":"74175efecabdb8e5f43531beab38a64203b0331f"}},{"cell_type":"code","source":"# Author: Robert Kern\n\nZ = np.random.randint(0,5,(10,3))\nprint(Z)\n# solution for arrays of all dtypes (including string arrays and record arrays)\nE = np.all(Z[:,1:] == Z[:,:-1], axis=1)\nU = Z[~E]\nprint(U)\n# soluiton for numerical arrays only, will work for any number of columns in Z\nU = Z[Z.max(axis=1) != Z.min(axis=1),:]\nprint(U)","metadata":{"_uuid":"2adc7d15835b2ac4e870db377555fff5a5da439b"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 95. Convert a vector of ints into a matrix binary representation (★★★)","metadata":{"_uuid":"5afd250a943d5e2f008bf0682376e140be69d007"}},{"cell_type":"code","source":"# Author: Warren Weckesser\n\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])\nB = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)\nprint(B[:,::-1])\n\n# Author: Daniel T. McDonald\n\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)\nprint(np.unpackbits(I[:, np.newaxis], axis=1))","metadata":{"_uuid":"2f25d28334b03e5cab6d6dc3e7312991acf8bb18"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 96. Given a two dimensional array, how to extract unique rows? (★★★)","metadata":{"_uuid":"c5a8dd39a51cf4dbe37653e3d6131d06ac7a449c"}},{"cell_type":"code","source":"# Author: Jaime Fernández del Río\n\nZ = np.random.randint(0,2,(6,3))\nT = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))\n_, idx = np.unique(T, return_index=True)\nuZ = Z[idx]\nprint(uZ)\n\n# Author: Andreas Kouzelis\n# NumPy >= 1.13\nuZ = np.unique(Z, axis=0)\nprint(uZ)","metadata":{"_uuid":"2015fb48f278ce0021a3aa8f98db67438d2d92a6"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)","metadata":{"_uuid":"d6b3ea56acfd5d993c47a9133717fe70f3475cb8"}},{"cell_type":"code","source":"# Author: Alex Riley\n# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/\n\nA = np.random.uniform(0,1,10)\nB = np.random.uniform(0,1,10)\n\nnp.einsum('i->', A) # np.sum(A)\nnp.einsum('i,i->i', A, B) # A * B\nnp.einsum('i,i', A, B) # np.inner(A, B)\nnp.einsum('i,j->ij', A, B) # np.outer(A, B)","metadata":{"_uuid":"7b358d49dc06cfd933516942d07cf909cccacb09"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?","metadata":{"_uuid":"6a56f94c7bf3d56ee49bff6da8d1cc73c0098cee"}},{"cell_type":"code","source":"# Author: Bas Swinckels\n\nphi = np.arange(0, 10*np.pi, 0.1)\na = 1\nx = a*phi*np.cos(phi)\ny = a*phi*np.sin(phi)\n\ndr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths\nr = np.zeros_like(x)\nr[1:] = np.cumsum(dr) # integrate path\nr_int = np.linspace(0, r.max(), 200) # regular spaced path\nx_int = np.interp(r_int, r, x) # integrate path\ny_int = np.interp(r_int, r, y)","metadata":{"_uuid":"e185595ef1c04a7adf0497a694c11912d9ff9e70","collapsed":true,"jupyter":{"outputs_hidden":true}},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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. (★★★)","metadata":{"_uuid":"5fb61ce6e7ea34a5b937334882106c1aa09d80a3"}},{"cell_type":"code","source":"# Author: Evgeni Burovski\n\nX = np.asarray([[1.0, 0.0, 3.0, 8.0],\n [2.0, 0.0, 1.0, 1.0],\n [1.5, 2.5, 1.0, 0.0]])\nn = 4\nM = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)\nM &= (X.sum(axis=-1) == n)\nprint(X[M])","metadata":{"_uuid":"2b2e13184b51ea3ca665a2decf66fffd55cef70c"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### 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). (★★★)","metadata":{"_uuid":"93abcae8fa323bad995c5f6db368c6d8b21d995b"}},{"cell_type":"code","source":"# Author: Jessica B. Hamrick\n\nX = np.random.randn(100) # random 1D array\nN = 1000 # number of bootstrap samples\nidx = np.random.randint(0, X.size, (N, X.size))\nmeans = X[idx].mean(axis=1)\nconfint = np.percentile(means, [2.5, 97.5])\nprint(confint)","metadata":{"_uuid":"c1db0f15a88199e936aad0928b15a8f3976fbb1e"},"execution_count":null,"outputs":[]}]}