Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Numpy for Data Science ?

Numpy

Uploaded by

Pankaj Singhi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
8 views

Numpy for Data Science ?

Numpy

Uploaded by

Pankaj Singhi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 9
Top 50 Numpy Exercises for Data Science - Cheatsheet . Import the numpy package under the name np (* x import numpy as np . Print the numpy version and the configuration (* ¥ x) print(np._version_) np.show_config() . Create a null vector of size 10 (* x9) Z = np.zeros(10) print(Z) . How to get the documentation of the numpy add function from the command line? (x vrs) python -c “import numpy; numpy.info(numpy.add)" . Create a null vector of size 10 but the fifth value which is 1 (vv) Z = np.zeros(10) Z{4] =1 print(Z) . Create a vector with values ranging from 10 to 49 (# x Z = np.arange(10,50) print(Z) . Reverse a vector (first element becomes last) (* x* v) -arange(50) ri-1] @ © 10. 11, 12, 13. 14. Create a 3x3 matrix with values ranging from 0 to 8 (*¥ Z = np.arange(9).reshape(3,3) print(Z) Find indices of non-zero elements from [1,2,0,0,4,0] (* > x) nz = np.nonzero([1,2,0,0,4,0]) print(nz) Create a 3x3 identity matrix (* >: Z = np.eye(3) print(Z) Create a 3x3x3 array with random values (* ¥ Z = np.random. random((3,3,3)) print(Z) Create a 10x10 array with random values and find the minimum and maximum values (sxx) Z = np.random. random((10,16)) Zmin, Zmax = Z.min(), Z.max() print(Zmin, Zmax) Create a random vector of size 30 and find the mean value (* Z = np.random. random(30) m = Z.mean() print(m) Create a 2d array with 1 on the border and 0 inside (* xr) Z = np.ones((10,10)) Z[l:-1,1:-1] = 0 15. What is the result of the following expression? (x +r) ® * np.nan np.nan == np.nan np.inf > np.nan np.nan - np.nan 16. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (*¥ Z = np.diag(1+np.arange(4),k=-1) print(Z) 17. Create a 8x8 matrix and fill it with a checkerboard pattern (*« Z = np.zeros((8,8) ,dtype=int) 2(e12,2:2] = 1 Z[2:2,1::2] = 1 print(Z) 18. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? print (np.unravel_index(100, (6,7,8))) 19. Create a checkerboard 8x8 matrix using the tile function (* y+) Z = np.tile( np.array({[0,1],[1,0]]), (4,4) print(Z) 20. Normalize a 5x5 random matrix (* vv) Z = np.random.random((5,5)) 2max, Zmin = Z.max(), Z.min() Z = (Z - Zmin)/(Zmax'- Zmin) print(Z) 21. Create a custom dtype that describes a color as four unisgned bytes (RGBA) (kye xr) r", np.ubyte, 1), Hg" color = np.dtype(L a np.ubyte, 1), np.ubyte, 1), np.ubyte, 1)]) 22. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (+ s+) Z = np.dot(np.ones((5,3)), np.ones((3,2))) print (Z) 23. Given a 1D array, negate all elements which are between 3 and 8, in place. (aoe) # Author: Evgeni Burovski Z = np.arange(11) ZU(3 < Z) & (Z <= 8)] *= -1 24. What is the output of the following script? (* ¥ +) # Author: Jake VanderPlas print (sum(range(5),-1)) from numpy import * print (sum(range(5),-1)) 25. Consider an integer vector Z, which of these expressions are legal? (* + anez 2<>2 Z<-Z 1j*Z zl ZZ 26. What are the result of the following expressions? np.array(®) // np.array(0) np.array(0) // np.array(@.) np.array(0) / np.array(@) np.array(0) / np.array(@.) 27. How to round away from zero a float array ? (* vr) # Author: Charles R Harris Z = np.random.uniform(-10,+10,10) print (np.trunc(Z + np.copysign(®.5, Z))) 28. Extract the integer part of a random array using 5 different methods (* * xr) Z = np.random.uniform(0,10,10) print (Z - 2%1) print (np.floor(Z)) print (np.ceil(Z)-1) print (Z.astype(int)) print (np.trunc(Z)) 29. Create a 5x5 matrix with row values ranging from 0 to 4 (* >) Z = np.zeros((5,5)) Z += np.arange(5) print(Z) 30. Consider a generator function that generates 10 integers and use it to build an array (* vr vr) def generate(): for x in xrange(10): yield x Z = np.fromiter(generate() ,dtype=float, count=-1) print(Z) 31. 32. 33. 34. 35. 36. Create a vector of size 10 with values ranging from 0 to 1, both excluded (* * 7) Z = np. Linspace(0,1,12, endpoint=True) [1:-1] print(Z) Create a random vector of size 10 and sort it (* * 7) Z = np. random. random(10) Z.sort() print(Z) How to sum a small array faster than np.sum? (* * ¥) # Author: Evgeni Burovski Z = np.arange(10) np.add. reduce (Z) Consider two random array A anb B, check if they are equal (* * vr) A = np.random.randint(0,2,5) B = np. random. randint (0,2,5) equal = np.allclose(A,B) print (equal) Make an array immutable (read-only) (* * +) Z = np.zeros(10) Z.flags.writeable = False Z{0] =1 Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (* #) np. random. random((10,2)) = 2[:,0], Z[:,1] np. sqrt (X**2#Y**2) np.arctan2(Y,X) print(R) print(T) 37. Create random vector of size 10 and replace the maximum value by 0 (*«* 7) Z = np. random. random(10 2[Z.argmax()] = 0 print(Z) 38. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (ks) Z = np.zeros((10,10), [('x', float), ('y', float)]) ZU'x'], Z['y'] = np.meshgrid(np.linspace(9,1,10), np. Linspace(0,1,10)) print(Z) 39. Given two arrays, X and Y, construct the Cauchy matrix C (Cij = 1/(xi - yj)) # Author: Evgeni Burovski X = np.arange(8) X+0.5 C = 1.0 / np.subtract.outer(X, Y) print (np. Linalg. det (C)) 40. Print the minimum and maximum representable value for each numpy scalar type (4S) for dtype in [np.int8, np.int32, np.int64]: print (np.iinfo(dtype) .min) print (np.iinfo(dtype) .max) for dtype in [np.float32, np.floaté4] print (np. finfo(dtype) .min) print (np. finfo(dtype) .max) print (np. finfo(dtype) .eps) 41, How to print all the values of an array? (* * x) np.set_printoptions(threshold=np. nan’ Z = np.zeros((25,25)) print(Z) 42. How to find the closest value (to a given scalar) in an array? (* * ¥) Z = np.arange(100) v = np.random.uniform(0,100) index = (np.abs(Z-v)).argmin() print (Z[index]) 43. Create a structured array representing a position (x,y) and a color (1,g,b) («* Z = np.zeros(10, [ ('position', [ ('x', float, 1), ('y', float, 1)1), (‘color', — [ (‘r', float, 1), (‘g', float, 1), ('b', float, 1)])]) print(Z) 44. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (*« *s*°) Z = np. random. random((10,2)) X,Y = np.atleast_2d(Z[:,0]), np.atleast_2d(Z[:,1]) D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2) print(D) # Much faster with scipy import scipy # Thanks Gavin Heverly-Coulson (#issue 1) import scipy.spatial np. random. random( (10,2) ) Zs D = scipy. spatial. distance. cdist(Z,Z) print(D) 45. How to convert a float (32 bits) array into an integer (32 bits) in place? np.arange(10, dtype=np. int32) Z.astype(np.float32, copy=False) 46. How to read the following file? (* * sx) # File content: 6,,,7,8 219,10,11 Z = np.genfromtxt("missing.dat", delimiter=",") 47. What is the equivalent of enumerate for numpy arrays? (*« * x) Z = np.arange(9) . reshape(3,3) for index, value in np.ndenumerate(Z): print(index, value) for index in np.ndindex(Z.shape) : print(index, Z[index]) 48. Generate a generic 2D Gaussian-like array (* *¥) X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10)) D = np.sqrt (X*X+Y*Y) sigma, mu = 1.0, 0.0 G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) ) print(G) 49. How to randomly place p elements in a 2D array? (* * x) # Author: Divakar n= 10 p=3 Z = np.zeros((n,n)) np.put(Z, np.random.choice(range(n*n), p, replace=False) ,1) 50. Subtract the mean of each row of a matrix (* * vr) # Author: Warren Weckesser X = np.random.rand(5, 10) Recent versions of numpy =X - X.mean(axis=1, keepdims=True) <% Older versions of numpy = X - X.mean(axis=1).reshape(-1, 1) <4

You might also like