Vortex.ihrc.fiu.edu



Numpy-BasicsNumpy arrayPython list is powerful, but they can confuse programmers familiar with other languages and may not be easy to learn/use for beginners. Numpy provides a much better array object. Assuming you have Numpy installed (see Lecture 1), all you need to do is to import it,?>>> import numpy >>> import numpy as npThen, you can use np as prefix to the start of any program.The main thing that Numpy brings to the environment is the Numpy array, which is an object that wraps a static array of various data types.Note that the Numpy array is a completely separate data structure from the Python list, which means you can have two types of array-like entity within your program. The good news is that it is very easy to convert Python lists that are "array-like" to Numpy arrays. A key difference is that the elements of a Numpy array are all of the same type and have a fixed and very specific data type once created.1 Create a Numpy array 1.1 You can use the low level constructor ‘ndarray’ to create an array. For example,>>> myArray=np.ndarray((3,3))It creates a 3 by 3 array of floats. The array is created in memory but uninitialized. This means that if you try to make use of any of the elements of myArray you will find some random garbage.?1.2 A more usual way of creating an array is to use np.zeros or?np.ones, for example,>>> myArray=np.zeros((3,3))>>> myArray=np.ones((3,3))1.3 You can use ‘np.arange(start,end,increment)’ to create a one dimensional array initialized to values from start to end spaced by increment, for example,>>> var= np.arange(0,10,0.2)>>> x = np.arange(9.)>>> xarray([ 0., 1., 2., 3., 4., 5., 6., 7., 8.])1.4 ‘linspace’ method can be used to create an array of a specified size with evenly spaced values. ?For example,>>> var=np.linspace(2.0, 3.0, num=5)>>> vararray([ 2. , 2.25, 2.5 , 2.75, 3. ])1.5 Using numpy ‘full’ method to generate constant array, for example>>> c = np.full((2,2), 7, dtype=np.float)>>> carray([[ 7., 7.], [ 7., 7.]])>>> c = np.full((2,2), 7, dtype=np.int)>>> carray([[7, 7], [7, 7]])>>> c = np.full((2,2), np.inf)>>> carray([[ inf, inf], #inf: infinity [ inf, inf]])>>> c = np.full((2,2), np.nan)>>> carray([[ nan, nan], [ nan, nan]])#nan: stands for "Not a Number".Numpy supports a much greater variety of numerical types than Python does. The table below shows which are available, and how to modify an array’s data-type.Data typeDescriptionbool_Boolean (True or False) stored as a byteint_Default integer type (same as C long; normally either int64 or int32)IntcIdentical to C int (normally int32 or int64)IntpInteger used for indexing (same as C ssize_t; normally either int32 or int64)int8Byte (-128 to 127)int16Integer (-32768 to 32767)int32Integer (-2147483648 to 2147483647)int64Integer (-9223372036854775808 to 9223372036854775807)uint8Unsigned integer (0 to 255)uint16Unsigned integer (0 to 65535)uint32Unsigned integer (0 to 4294967295)uint64Unsigned integer (0 to 18446744073709551615)float_Shorthand for float64.float16Half precision float: sign bit, 5 bits exponent, 10 bits mantissafloat32Single precision float: sign bit, 8 bits exponent, 23 bits mantissafloat64Double precision float: sign bit, 11 bits exponent, 52 bits mantissacomplex_Shorthand for plex64Complex number, represented by two 32-bit floats (real and imaginary components)complex128Complex number, represented by two 64-bit floats (real and imaginary components)Additionally to intc the platform dependent C integer types short, long, longlong and their unsigned versions are defined.1.6 Using numpy ‘eye’ method to generate identity matrix, for example,>>> d = np.eye(5)>>> darray([ [ 1., 0., 0., 0., 0.],[ 0., 1., 0., 0., 0.], [ 0., 0., 1., 0., 0.], [ 0., 0., 0., 1., 0.], [ 0., 0., 0., 0., 1.]])1.7 Using numpy ‘random’ method to generate an array with random values, for example,>>> e = np.random.random((3,5))>>> earray([[ 0.87326331, 0.86135152, 0.82519615, 0.42955884, 0.7226091 ], [ 0.44400687, 0.21482084, 0.48345701, 0.78465047, 0.06067008], [ 0.70525464, 0.024604 , 0.48172213, 0.36605474, 0.43707372]])Try>>> e = np.random.random((3))>>> e = np.random.random((3,5,4))1.8 You can use the ‘array’ method to convert a Python list object into a Numpy array. For example:>>> mylist=[[1,2,3],[4,5,6],[7,8,9]]>>> mylist[[1, 2, 3], [4, 5, 6], [7, 8, 9]]>>>myarray=np.array(mylist)>>> myarrayarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])2. Numpy Array SlicingRecall in Python list we can use the following method to select a specific element of the list, for example,>>> mylist[0][2]3In Numpy, we can use the following method to select a specific element of the array similar to other languages, for example,>>> myarray[0,2]3You can also define a sub-list or sub-array using slicing, for example,>>> mylist[0:2][[1, 2, 3], [4, 5, 6]]But how to define a sub-list [[1,2],[4,5]] from the list [[1, 2, 3], [4, 5, 6], [7, 8, 9]]? It is not easy using list slicing. Still you could do it using, >>> list(zip(*list(zip(*mylist[0:2]))[0:2]))[(1, 2), (4, 5)]This does not look easy at all although it works. This can be done easily in numpy array!>>> myarray[0:2,0:2]array([[1, 2], [4, 5]])This is similar to Matlab, c++,..and other languages.3. Transposing an array,>>> np.transpose(myarray)array([[1, 4, 7], [2, 5, 8], [3, 6, 9]])This is equivalent to >>> myarray.Tarray([[1, 4, 7], [2, 5, 8], [3, 6, 9]])4. Dimension of an arrayYou can use the following method to return the dimension of an array,>>>X= [[12, 7, 3, 4], [4, 5, 6, 5], [7, 8, 9, 6]]>>> X1=np.array(X)>>> X1array([[12, 7, 3, 4], [ 4, 5, 6, 5], [ 7, 8, 9, 6]])>>> X1.shape(3, 4) It means that X1 has three rows and four columns.5. Reshaping an array,>>>X2=X1.reshape(2,6)>>> X2array([[12, 7, 3, 4, 4, 5], [ 6, 5, 7, 8, 9, 6]])6. Boolean indexing>>> myarrayarray([ [1, 2, 3], [4, 5, 6], [7, 8, 9]])>>> myarray>1array([[False, True, True], [ True, True, True], [ True, True, True]], dtype=bool)This makes it easy to index an array on a condition. For example, suppose you wanted to reset every element of the following array smaller than 5 to zero:>>> X1array([[12, 7, 3, 4], [ 4, 5, 6, 5], [ 7, 8, 9, 6]])>>> X1[X1<5]=0>>> X1array([[12, 7, 0, 0], [ 0, 5, 6, 5], [ 7, 8, 9, 6]])7. Find elements in an array satisfying a condition>>> x = np.arange(9.)>>> xarray([ 0., 1., 2., 3., 4., 5., 6., 7., 8.])>>> x = np.arange(9.).reshape(3, 3)>>> xarray([ [ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]])>>> np.where( x > 5 )(array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))>>> x[np.where( x > 3.0 )] # Note: result is 1D.array([ 4., 5., 6., 7., 8.])8. Convert array data type using astype>>> x = np.array([1.1, 2.3, 2.5])>>> xarray([ 1.1, 2.3, 2.5])>>> y=x.astype(int)>>> yarray([1, 2, 2])>>> x=y.astype(float)>>> xarray([ 1., 2., 2.])One more example,>>> Xarray([[12, 7, 3, 4], [ 4, 5, 6, 5], [ 7, 8, 9, 6]])X[X>5]=np.nanTraceback (most recent call last): File "<pyshell#90>", line 1, in <module> X[X>5]=np.nanValueError: cannot convert float NaN to integer>>> X=X.astype(float)>>> Xarray([[ 12., 7., 3., 4.], [ 4., 5., 6., 5.], [ 7., 8., 9., 6.]])>>> X[X>5]=np.nan>>> Xarray([[ nan, nan, 3., 4.], [ 4., 5., nan, 5.], [ nan, nan, nan, nan]])>>> np.isnan(X)array([[ True, True, False, False], [False, False, True, False], [ True, True, True, True]], dtype=bool)>>> X[np.isnan(X)]array([ nan, nan, nan, nan, nan, nan, nan])>>> X[np.isnan(X)==False]array([ 3., 4., 4., 5., 5.])9. Combining arrays using numpy ‘concatenate’ command and splitting an array using ‘split’>>> a = np.array([[1, 2], [3, 4]])>>> b = np.array([[5, 6]])>>> np.concatenate((a, b), axis=0)array([[1, 2], [3, 4], [5, 6]])>>> np.concatenate((a, b.T), axis=1)array([[1, 2, 5], [3, 4, 6]])>>> x = np.arange(9.0)>>> xarray([ 0., 1., 2., 3., 4., 5., 6., 7., 8.])>>> np.split(x, 3)[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]>>> [a, b, c]=np.split(x, 3)>>> aarray([ 0., 1., 2.])>>> barray([ 3., 4., 5.])>>> carray([ 6., 7., 8.])10. Array math10.1 Addition, subtraction, multiplication, division>>>x= [[12, 7, 3, 4], [4, 5, 6, 5], [7, 8, 9, 6]]>>>y= [[5, 8, 1, 3], [6, 7, 3, 8], [4, 5, 9, 7]]>>> X=np.array(x)>>> Xarray([[12, 7, 3, 4], [ 4, 5, 6, 5], [ 7, 8, 9, 6]])>>> Y=np.array(y)>>> Yarray([[5, 8, 1, 3], [6, 7, 3, 8], [4, 5, 9, 7]])>>> Z=X+Y>>> Zarray([[17, 15, 4, 7], [10, 12, 9, 13], [11, 13, 18, 13]])>>> Z=np.add(X,Y)>>> Zarray([[17, 15, 4, 7], [10, 12, 9, 13], [11, 13, 18, 13]])>>> W=X-Y>>> Warray([[ 7, -1, 2, 1], [-2, -2, 3, -3], [ 3, 3, 0, -1]])>>> W=np.subtract(X,Y)>>> Warray([[ 7, -1, 2, 1], [-2, -2, 3, -3], [ 3, 3, 0, -1]])>>> Z=X*Y>>> Zarray([[60, 56, 3, 12], [24, 35, 18, 40], [28, 40, 81, 42]])>>> Z=np.multiply(X,Y)>>> Zarray([[60, 56, 3, 12], [24, 35, 18, 40], [28, 40, 81, 42]])>>> Z=X/Y>>> Zarray([[ 2.4 , 0.875 , 3. , 1.33333333], [ 0.66666667, 0.71428571, 2. , 0.625 ], [ 1.75 , 1.6 , 1. , 0.85714286]])>>> Z=np.divide(X,Y)>>> Zarray([[ 2.4 , 0.875 , 3. , 1.33333333], [ 0.66666667, 0.71428571, 2. , 0.625 ], [ 1.75 , 1.6 , 1. , 0.85714286]])10.2 Matrix multiplication>>> W=X.dot(np.transpose(Y))>>> Warray([[131, 162, 138], [ 81, 117, 130], [126, 173, 191]])>>> W=np.dot(X, np.transpose(Y))>>> Warray([[131, 162, 138], [ 81, 117, 130], [126, 173, 191]]) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download