Import the numpy package under the name np
(★☆☆) (hint : import … as …)
Print the numpy version (★☆☆) (hint : np.__version__)
Create a vector of zeros of size 10 (★☆☆) (hint : np.zeros)
How to find the memory size of any array (★☆☆) (hint : size, itemsize)
1 2 print (vec.size, vec.itemsize)print (vec.size * vec.itemsize)
Create am zero vector of size 10 but the fifth value which is 1 (★☆☆) (hint : array[4])
Create a vector with values ranging from 10 to 49 (★☆☆) (hint : np.arange)
1 vec_range = np.arange(10 , 50 )
Reverse a vector (first element becomes last) (★☆☆) (hint : array[::-1])
1 vec_range = vec_range[::-1 ]
Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆) (hint : reshape)
1 2 mat = np.arange(0 , 9 ) mat = mat.reshape(3 , 3 )
Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆) (hint : np.nonzero)
1 np.nonzero([1 , 2 , 0 , 0 , 4 , 0 ])
Create a 3x3 identity matrix (★☆☆) (hint : np.eye)
1 identity_mat = np.eye(3 )
Create a 3x3x3 array with random values (★☆☆) (hint : np.random.random)
1 2 tensor = np.random.random(27 ) tensor = tensor.reshape(3 , 3 , 3 )
Create a 10x10 array with random values and find the minimum and maximum values (★☆☆) (hint : min, max)
1 2 3 arr = np.random.random(100 ).reshape(10 , 10 ) print (arr)print (np.max (arr), np.min (arr))
Create a random vector of size 30 and find the mean value (★☆☆) (hint : mean)
1 2 3 mean_vec = np.random.random(30 ) print (mean_vec)print (np.mean(mean_vec))
Create a 2d array with 1 on the border and 0 inside (★☆☆) (hint : array[1:-1, 1:-1])
1 2 arr_2D = np.ones(100 ).reshape(10 , 10 ) arr_2D[1 :-1 , 1 :-1 ] = 0
How to add a border (filled with 0’s) around an existing array? (★☆☆) (hint : np.pad)
1 arr_2D = np.pad(arr_2D, 1 )
What is the result of the following expression? (★☆☆) (hint : NaN = not a number, inf = infinity)1 2 3 4 5 0 * np.nannp.nan == np.nan np.inf > np.nan np.nan - np.nan 0.3 == 3 * 0.1
note: np.isclose
is useful when rounding error occurs
1 2 3 4 5 print (0 * np.nan)print (np.nan == np.nan)print (np.inf > np.nan)print (np.nan - np.nan)print (0.3 == 3 * 0.1 )
Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆) (hint : np.diag)
1 2 3 4 5 mat2 = np.zeros(25 ).reshape(5 , 5 ) mat2[0 ][0 ] = 1 mat2[0 ][4 ] = 2 mat2[4 ][0 ] = 3 mat2[4 ][4 ] = 4
Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆) (hint : array[::2])
1 2 3 4 5 checkerboard = np.zeros(81 ) checkerboard[::2 ] = 1 checkerboard = checkerboard.reshape(9 , 9 ) checkerboard = np.delete(checkerboard, 8 , axis = 1 ) checkerboard = np.delete(checkerboard, 8 , axis = 0 )
Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (hint : np.unravel_index)
1 rk100 = np.unravel_index(100 , (6 , 7 , 8 ))
Create a checkerboard 8x8 matrix using the tile function (★☆☆) (hint : np.tile)
1 2 checkerboard2 = np.eye(2 ) checkerboard2 = np.tile(checkerboard2, (4 , 4 ))
Normalize a 5x5 random matrix (★☆☆) (hint : (x - min) / (max - min))
1 2 3 4 Nmat = np.random.random(25 ) maxn = np.max (Nmat) minn = np.min (Nmat) Nmat = (Nmat-minn)/(maxn-minn)
Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆) (hint : np.dtype)
1 RGBA = np.dtype([('R' , np.ubyte), ('G' , np.ubyte), ('B' , np.ubyte), ('A' , np.ubyte)])
Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆) (hint : np.dot | @)
1 2 3 mat1 = np.random.random(15 ).reshape(5 , 3 ) mat2 = np.random.random(6 ).reshape(3 , 2 ) mat3 = mat1 @ mat2
Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆) (hint : >, <=)
1 2 arr38 = np.random.randint(1 , high = 10 , size = 10 ) arr38[((arr38<8 ) & (arr38>3 ))] *= -1
What is the output of the following script? Why? (★☆☆) (hint : np.sum)1 2 3 4 5 print (sum (range (5 ),-1 ))import numpy as npprint (np.sum (range (5 ),-1 ))
1 2 print (sum (range (5 ), -1 ))print (np.sum (range (5 ), -1 ))
Consider an integer vector Z, which of these expressions are legal? (★☆☆) 1 2 3 4 5 6 Z**Z 2 << Z >> 2 Z <- Z 1j *ZZ/1 /1 Z<Z>Z
1 2 3 4 5 6 Z = np.array([1 , 2 , 3 ]) print (Z**Z)print (2 << Z >> 2 )print (Z < -Z)print (1j *Z)print (Z/1 /1 )\
What are the result of the following expressions? 1 2 3 np.array(0 ) / np.array(0 ) np.array(0 ) // np.array(0 ) np.array([np.nan]).astype(int ).astype(float )
1 2 3 print (np.array(0 ) / np.array(0 ))print (np.array(0 ) // np.array(0 ))print (np.array([np.nan]).astype(int ).astype(float ))
How to round away from zero a float array ? (★☆☆) (hint : np.uniform, np.copysign, np.ceil, np.abs)
1 2 3 roundarr = np.random.uniform(-10 , 10 , 10 ) print (roundarr)roundarr = np.copysign(np.ceil(np.abs (roundarr)), roundarr)
How to find common values between two arrays? (★☆☆) (hint : np.intersect1d)
1 2 3 4 arr1 = np.random.randint(1 , 10 , 8 ) arr2 = np.random.randint(1 , 10 , 8 ) arr3 = np.intersect1d(arr1, arr2) print (arr1, arr2, arr3)
How to ignore all numpy warnings (not recommended)? (★☆☆) (hint : np.seterr, np.errstate)
1 settings = np.seterr(all = 'ignore' )
Is the following expressions true? (★☆☆) (hint : imaginary number)1 np.sqrt(-1 ) == np.emath.sqrt(-1 )
1 print (np.sqrt(-1 ) == np.emath.sqrt(-1 ))
How to get the dates of yesterday, today and tomorrow? (★☆☆) (hint : np.datetime64, np.timedelta64)
1 2 3 4 yesterday = np.datetime64("Today" , "D" ) - np.timedelta64(1 , "D" ) today = np.datetime64("Today" , "D" ) tomorrow = np.datetime64("Today" , "D" ) + np.timedelta64(1 , "D" ) print (yesterday, today, tomorrow)
How to get all the dates corresponding to the month of July 2016? (★★☆) (hint : np.arange(dtype=datetime64[‘D’]))
1 date_arr = np.arange("2016-07" , "2016-08" , dtype = "datetime64[D]" )
How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆) (hint : np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=))
1 2 3 4 5 6 A = np.eye(3 ) B = np.eye(3 ) np.add(A, B, out = B) np.divide(A, 2 , out = A) np.negative(A, out = A) np.multiply(B, A, out = A)
Extract the integer part of a random array using 5 different methods (★★☆) (hint : %, np.floor, np.ceil, astype, np.trunc)
1 2 3 4 5 intarr = np.random.uniform(-10 , 10 , 10 ) intarr = intarr.astype('int64' ) intarr
Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆) (hint : np.arange)
1 2 mat04 = np.zeros([5 , 5 ]) mat04 += np.arange(0 , 5 )
Consider a generator function that generates 10 integers and use it to build an array (★☆☆) (hint : np.fromiter)
1 2 3 4 5 def func (): for i in range (10 ): yield i arr = np.fromiter(func(), dtype = 'int64' )
Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆) (hint : np.linspace)
1 arr = np.linspace(0 , 1 , 11 , endpoint = False )[1 :]
Create a random vector of size 10 and sort it (★★☆) (hint : sort)
1 2 3 St = np.random.uniform(-10 , 10 , 10 ) St.sort()
How to sum a small array faster than np.sum? (★★☆) (hint : np.add.reduce)
1 2 arr = np.arange(10 ) res = np.add.reduce(arr)
Consider two random array A and B, check if they are equal (★★☆) (hint : np.allclose, np.array_equal)
1 2 3 4 arr1 = np.arange(10 ) arr2 = np.arange(10 ) res = np.array_equal(arr1, arr2)
Make an array immutable (read-only) (★★☆) (hint : flags.writeable)
1 2 arr = np.arange(10 ) arr.flags.writeable = 0
Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆) (hint : np.sqrt, np.arctan2)
1 2 3 4 5 6 arr = np.random.randint(-10 , 10 , (10 , 2 )) x = arr[:, 0 ] y = arr[:, 1 ] r = np.sqrt(x**2 +y**2 , dtype = 'float16' ) theta = np.arctan2(x, y) arr = np.array([r, theta]).T
Create random vector of size 10 and replace the maximum value by 0 (★★☆) (hint : argmax)
1 2 mat = np.random.random(10 ) mat[np.argmax(mat)] = 0
Create a structured array with x
and y
coordinates covering the [0,1]x[0,1] area (★★☆) (hint : np.meshgrid)1 2 3 4 5 [[(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. )]]
1 2 mat = np.zeros((5 ,5 ), [('x' ,float ),('y' ,float )]) mat['x' ], mat['y' ] = np.meshgrid(np.linspace(0 ,1 ,5 ),np.linspace(0 ,1 ,5 ))
Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (hint : np.subtract.outer)
1 2 3 matx = np.arange(5 ) maty = matx - 0.5 matc = 1 /np.subtract.outer(matx, maty)
Print the minimum and maximum representable value for each numpy scalar type (★★☆) (hint : np.iinfo, np.finfo, eps)
1 2 3 4 5 6 7 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.float64]: print (np.finfo(dtype).min ) print (np.finfo(dtype).max ) print (np.finfo(dtype).eps)
Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆) (hint : np.atleast_2d, T, np.sqrt)
1 2 3 vec = np.random.rand(5 , 2 ) vecx, vecy = np.atleast_2d(vec[:,0 ], vec[:,1 ]) dis = np.sqrt((vecx.T - vecx) ** 2 + (vecy.T - vecy) ** 2 )
How to convert a float (32 bits) array into an integer (32 bits) in place? (hint : astype(copy=False))
1 2 vec = np.arange(10 , dtype = np.float32) vec = vec.astype(np.int32, copy=False )
What is the equivalent of enumerate for numpy arrays? (★★☆) (hint : np.ndenumerate, np.ndindex)
1 2 3 4 5 mat = np.arange(9 ).reshape(3 ,3 ) for index, value in np.ndenumerate(mat): print (index, value) for index in np.ndindex(mat.shape): print (index, mat[index])
How to randomly place p elements in a 2D array? (★★☆) (hint : np.put, np.random.choice)
1 2 3 4 5 p = 10 mat = np.arange(100 ).reshape(10 , 10 ) print (mat)np.put(mat, np.random.choice(range (10 * 10 ), p, replace = False ), 1 ) print (mat)
Subtract the mean of each row of a matrix (★★☆) (hint : mean(axis=,keepdims=))
1 2 3 mat = np.random.randint(1 , 10 , (5 , 10 )) print (mat)mat = mat - mat.mean(axis=1 , keepdims=True )
How to sort an array by the nth column? (★★☆) (hint : argsort)
1 2 3 4 n = 1 mat = np.random.randint(0 , 10 , (3 , 3 )) print (mat)mat = mat[mat[:,n].argsort()]
Find the nearest value from a given value in an array (★★☆) (hint : np.abs, argmin, flat)
in array([0.28428161, 0.25229009, 0.80514467, 0.76970704, 0.17243769,
0.31141961, 0.24836806, 0.63500349, 0.41708633, 0.87628688])
the nearest value to 0.5
is 0.41708633
1 2 3 4 mat = np.array([0.28428161 , 0.25229009 , 0.80514467 , 0.76970704 , 0.17243769 ,0.31141961 , 0.24836806 , 0.63500349 , 0.41708633 , 0.87628688 ]) num = 0.4 ans = mat.flat[np.abs (mat - num).argmin()] print (ans)
How to count elements of an integer vector (X) to an array (F) based on an index list (I)? (★★★) (hint : np.bincount)1 2 3 4 X = [1 ,2 ,3 ,4 ,5 ,6 ] I = [1 ,3 ,9 ,3 ,4 ,1 ] print (F)
1 [0. 7. 0. 6. 5. 0. 0. 0. 0. 3.]
1 2 3 4 X = [1 ,2 ,3 ,4 ,5 ,6 ] I = [1 ,3 ,9 ,3 ,4 ,1 ] F = np.bincount(I,X) print (F)
Considering a four dimensions array, how to get sum over the last two axis at once? (★★★) (hint : sum(axis=(-2,-1)))
1 2 tensor = np.random.randint(1 , 10 , (4 , 4 , 4 , 4 )) tensor = tensor.sum (axis = (-2 , -1 ))