OBJECTIVE



LAB # 09NUMPYOBJECTIVEN-dimensional array using NumPy library in python.THEORYIntroduction:Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific computing. NumPy is one of the efficient open-source add-on modules to python that provide common mathematical and numerical routines in pre-compiled, fast functions.NumPy?(Numeric Python)?is a library for the?Python programming language, adding support for large, multi-dimensional?arrays?and?matrices, along with a large collection of?high-level mathematical?functions?to operate on these arrays.Installation:Installation files available at: the link on this page to download the official releases, which will be in the form of .whl file, install file for Windows. After the successful download then follow the instruction for installation NumPy library:Steps:Save/Copy NumPy (.whl) file in the same folder where python was installedOpen command prompt and change directory where the python was installedCheck currentdirectory(dir) and then install wheel file with the help of pip, pip?is apackage management system used to install and manage software packages written in?Python.“pip install wheel”After successful installation of wheel file then install NumPy library“pip install numpy”Importing the NumPy module:There are several ways to import NumPy. The standard approach is to use a simple import statement:import numpy However, for large amounts of calls to NumPy functions, it can become tedious to write numpy.X over and over again. Instead, it is common to import under the briefer name np: Import numpy as npThis statement will allow us to access NumPy objects using np.X instead of numpy. It is also possible to import NumPy directly into the current namespace so that we don't have to use dot notation at all, but rather simply call the functions as if they were built-in: from numpy import * In this statement, ?all functions will be loaded into the local namespace.Arrays in NumPy:?NumPy’s main object is the homogeneous multidimensional array.It is a table of elements (usually numbers), all of the same type.In NumPy dimensions are called?axes. The number of axes is?rank.NumPy’s array class is called?ndarray. It is also known by the alias?array.Example :[[ 1, 2, 3], [ 4, 2, 5]]Here,rank = 2 (as it is 2-dimensional or it has 2 axes)first dimension(axis) length = 2, second dimension has length = 3overall shape can be expressed as: (2, 3)ndarray: The N-dimensional arrays:The central feature of NumPy is the array object class. Arrays are similar to lists in Python, except that every element of an array must be of the same type, typically a numeric type like float or int. Arrays make operations with large amounts of numeric data very fast and are generally much more efficient than lists.Use the np.array ( ) constructor to create an array with any number of dimensions.np.array (object, dtype=None)Values to be used in creating the array. This can be a sequence (to create a 1-d array), a sequence of sequences (for a 2-d array), a sequence of sequences of sequences, and so on. Each sequence may be either a list or a tuple. To force the new array to be a given type, use one of the type words as the second argument. For example, array ([1, 2, 3], dtype=np.float_) will give you an array with those three values converted to floating-point type.Example:Representation of 1D, 2D, 3D array:One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensional as lists of matricesa = np.arange(6) # 1d array>>>print(a)[0 1 2 3 4 5]>>> b = np.arange(12).reshape(4,3) # 2d array>>>print(b)[[ 0 1 2][ 3 4 5][ 6 7 8][ 9 10 11]]>>>>>> c = np.arange(24).reshape(2,3,4) # 3d array>>> print(c)[[[ 0 1 2 3][ 4 5 6 7][ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]]Two-dimensional arrays:Arrays can be multidimensional. Unlike lists, different axes are accessed using commas inside bracket notation. Example: Output:lefttopYou can use slicing to get one row or column. A slice operation has this general form:M [rows, cols]In this form, rows and cols may be either regular Python slice operations (such as 2:5 to select the third through fifth items), or they may be just “:” to select all the elements in that dimension.In this example, we extract a 2×3 submatrix, containing rows 0 and 1, and columns 0, 1, and 2.Numpy array is very much similar to python list , so if we have python list, then why we need numpy array?There are several benefit using numpy array:Less memory over python listFastConvenientThe arange() function: Arithmetic progression:The np.arange() function to build a vector containing an arithmetic progression.arange([start,] stop[, step,][, dtype]) :?Returns an array with evenly spaced elements as per the interval. The interval mentioned is half opened i.e. [Start, Stop)Parameters :start : [optional] start of interval range. By default start = 0stop : end of interval rangestep : [optional] step size of interval. By default step size = 1, For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. dtype : type of output arrayBasic Functions:5:Example: Output:lefttopExample:The functions zeros and ones create new arrays of specified dimensions filled with these values. These are perhaps the most commonly used functions to create new arrays:The eye function returns matrices with ones along the kth diagonal:Example: Output: left22860 Array iteration:It is possible to iterate over arrays in a manner similar to that of lists:>>> a = np.array([1, 4, 5], int) >>> for x in a: print (x)For multidimensional arrays, iteration proceeds over the first axis such that each loop returns a subsection of the array:>>> a = np.array([[1, 2], [3, 4], [5, 6]], float) >>> for x in a: print (x) Multiple assignment can also be used with array iteration:>>> a = np.array([[1, 2], [3, 4], [5, 6]], float) >>> for (x, y) in a: print (x * y)Basic operations:Operations on single array:? We can use overloaded arithmetic operators to do element-wise operation on array to create a new array. In case of +=, -=, *= operators, the exsisting array is modified.Unary operators:?Many unary operations are provided as a method of?ndarray?class. This includes sum, min, max, etc. These functions can also be applied row-wise or column-wise by setting an axis parameter.Binary operators:?These operations apply on array elementwise and a new array is created. You can use all basic arithmetic operators like +, -, /,?, etc. In case of +=, -=,?= operators, the exsisting array is modified.Universal functions (ufunc):?NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These functions also operate elementwise on an array, producing an array as output.Lab#3 Exercise:Write a Python program to convert a list of numeric value into a one-dimensional NumPy array.Create a 3x3 matrix with values ranging from 2 to 10Create a null vector of size 15 and update fifth value to 12 and ninth value to 17Take 2D and 3D array and perform transpose function.Write a Python program to find the real and imaginary parts of an array of complex numbers.?Multiply a 5x3 matrix by a 3x2 matrix create a real matrix product using dot ( ).Create array by 2x3 and perform following function:Number of dimension(ndim)Total number of element/size in an arrayWhat type of array stores in memory(dtype)Write a Python program to create a 3-D array with ones on the diagonal and zeros elsewhere. ................
................

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

Google Online Preview   Download