Discuss NumPy ”; Previous Next NumPy, which stands for Numerical Python, is a library consisting of multidimensional array objects and a collection of routines for processing those arrays. Using NumPy, mathematical and logical operations on arrays can be performed. This tutorial explains the basics of NumPy such as its architecture and environment. It also discusses the various array functions, types of indexing, etc. An introduction to Matplotlib is also provided. All this is explained with the help of examples for better understanding. Print Page Previous Next Advertisements ”;
Category: numpy
NumPy – Mathematical Functions ”; Previous Next Quite understandably, NumPy contains a large number of various mathematical operations. NumPy provides standard trigonometric functions, functions for arithmetic operations, handling complex numbers, etc. Trigonometric Functions NumPy has standard trigonometric functions which return trigonometric ratios for a given angle in radians. Example Live Demo import numpy as np a = np.array([0,30,45,60,90]) print ”Sine of different angles:” # Convert to radians by multiplying with pi/180 print np.sin(a*np.pi/180) print ”n” print ”Cosine values for angles in array:” print np.cos(a*np.pi/180) print ”n” print ”Tangent values for given angles:” print np.tan(a*np.pi/180) Here is its output − Sine of different angles: [ 0. 0.5 0.70710678 0.8660254 1. ] Cosine values for angles in array: [ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17] Tangent values for given angles: [ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16] arcsin, arcos, and arctan functions return the trigonometric inverse of sin, cos, and tan of the given angle. The result of these functions can be verified by numpy.degrees() function by converting radians to degrees. Example Live Demo import numpy as np a = np.array([0,30,45,60,90]) print ”Array containing sine values:” sin = np.sin(a*np.pi/180) print sin print ”n” print ”Compute sine inverse of angles. Returned values are in radians.” inv = np.arcsin(sin) print inv print ”n” print ”Check result by converting to degrees:” print np.degrees(inv) print ”n” print ”arccos and arctan functions behave similarly:” cos = np.cos(a*np.pi/180) print cos print ”n” print ”Inverse of cos:” inv = np.arccos(cos) print inv print ”n” print ”In degrees:” print np.degrees(inv) print ”n” print ”Tan function:” tan = np.tan(a*np.pi/180) print tan print ”n” print ”Inverse of tan:” inv = np.arctan(tan) print inv print ”n” print ”In degrees:” print np.degrees(inv) Its output is as follows − Array containing sine values: [ 0. 0.5 0.70710678 0.8660254 1. ] Compute sine inverse of angles. Returned values are in radians. [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] Check result by converting to degrees: [ 0. 30. 45. 60. 90.] arccos and arctan functions behave similarly: [ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17] Inverse of cos: [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] In degrees: [ 0. 30. 45. 60. 90.] Tan function: [ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16] Inverse of tan: [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] In degrees: [ 0. 30. 45. 60. 90.] Functions for Rounding numpy.around() This is a function that returns the value rounded to the desired precision. The function takes the following parameters. numpy.around(a,decimals) Where, Sr.No. Parameter & Description 1 a Input data 2 decimals The number of decimals to round to. Default is 0. If negative, the integer is rounded to position to the left of the decimal point Example Live Demo import numpy as np a = np.array([1.0,5.55, 123, 0.567, 25.532]) print ”Original array:” print a print ”n” print ”After rounding:” print np.around(a) print np.around(a, decimals = 1) print np.around(a, decimals = -1) It produces the following output − Original array: [ 1. 5.55 123. 0.567 25.532] After rounding: [ 1. 6. 123. 1. 26. ] [ 1. 5.6 123. 0.6 25.5] [ 0. 10. 120. 0. 30. ] numpy.floor() This function returns the largest integer not greater than the input parameter. The floor of the scalar x is the largest integer i, such that i <= x. Note that in Python, flooring always is rounded away from 0. Example Live Demo import numpy as np a = np.array([-1.7, 1.5, -0.2, 0.6, 10]) print ”The given array:” print a print ”n” print ”The modified array:” print np.floor(a) It produces the following output − The given array: [ -1.7 1.5 -0.2 0.6 10. ] The modified array: [ -2. 1. -1. 0. 10.] numpy.ceil() The ceil() function returns the ceiling of an input value, i.e. the ceil of the scalar x is the smallest integer i, such that i >= x. Example Live Demo import numpy as np a = np.array([-1.7, 1.5, -0.2, 0.6, 10]) print ”The given array:” print a print ”n” print ”The modified array:” print np.ceil(a) It will produce the following output − The given array: [ -1.7 1.5 -0.2 0.6 10. ] The modified array: [ -1. 2. -0. 1. 10.] Print Page Previous Next Advertisements ”;
NumPy – Environment
NumPy – Environment ”; Previous Next Standard Python distribution doesn”t come bundled with NumPy module. A lightweight alternative is to install NumPy using popular Python package installer, pip. pip install numpy The best way to enable NumPy is to use an installable binary package specific to your operating system. These binaries contain full SciPy stack (inclusive of NumPy, SciPy, matplotlib, IPython, SymPy and nose packages along with core Python). Windows Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac. Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac. Python (x,y): It is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from https://www.python-xy.github.io/) Linux Package managers of respective Linux distributions are used to install one or more packages in SciPy stack. For Ubuntu sudo apt-get install python-numpy python-scipy python-matplotlibipythonipythonnotebook python-pandas python-sympy python-nose For Fedora sudo yum install numpyscipy python-matplotlibipython python-pandas sympy python-nose atlas-devel Building from Source Core Python (2.6.x, 2.7.x and 3.2.x onwards) must be installed with distutils and zlib module should be enabled. GNU gcc (4.2 and above) C compiler must be available. To install NumPy, run the following command. Python setup.py install To test whether NumPy module is properly installed, try to import it from Python prompt. import numpy If it is not installed, the following error message will be displayed. Traceback (most recent call last): File “<pyshell#0>”, line 1, in <module> import numpy ImportError: No module named ”numpy” Alternatively, NumPy package is imported using the following syntax − import numpy as np Print Page Previous Next Advertisements ”;
NumPy – Array Manipulation
NumPy – Array Manipulation ”; Previous Next Several routines are available in NumPy package for manipulation of elements in ndarray object. They can be classified into the following types − Changing Shape Sr.No. Shape & Description 1 reshape Gives a new shape to an array without changing its data 2 flat A 1-D iterator over the array 3 flatten Returns a copy of the array collapsed into one dimension 4 ravel Returns a contiguous flattened array Transpose Operations Sr.No. Operation & Description 1 transpose Permutes the dimensions of an array 2 ndarray.T Same as self.transpose() 3 rollaxis Rolls the specified axis backwards 4 swapaxes Interchanges the two axes of an array Changing Dimensions Sr.No. Dimension & Description 1 broadcast Produces an object that mimics broadcasting 2 broadcast_to Broadcasts an array to a new shape 3 expand_dims Expands the shape of an array 4 squeeze Removes single-dimensional entries from the shape of an array Joining Arrays Sr.No. Array & Description 1 concatenate Joins a sequence of arrays along an existing axis 2 stack Joins a sequence of arrays along a new axis 3 hstack Stacks arrays in sequence horizontally (column wise) 4 vstack Stacks arrays in sequence vertically (row wise) Splitting Arrays Sr.No. Array & Description 1 split Splits an array into multiple sub-arrays 2 hsplit Splits an array into multiple sub-arrays horizontally (column-wise) 3 vsplit Splits an array into multiple sub-arrays vertically (row-wise) Adding / Removing Elements Sr.No. Element & Description 1 resize Returns a new array with the specified shape 2 append Appends the values to the end of an array 3 insert Inserts the values along the given axis before the given indices 4 delete Returns a new array with sub-arrays along an axis deleted 5 unique Finds the unique elements of an array Print Page Previous Next Advertisements ”;
NumPy – Byte Swapping
NumPy – Byte Swapping ”; Previous Next We have seen that the data stored in the memory of a computer depends on which architecture the CPU uses. It may be little-endian (least significant is stored in the smallest address) or big-endian (most significant byte in the smallest address). numpy.ndarray.byteswap() The numpy.ndarray.byteswap() function toggles between the two representations: bigendian and little-endian. Live Demo import numpy as np a = np.array([1, 256, 8755], dtype = np.int16) print ”Our array is:” print a print ”Representation of data in memory in hexadecimal form:” print map(hex,a) # byteswap() function swaps in place by passing True parameter print ”Applying byteswap() function:” print a.byteswap(True) print ”In hexadecimal form:” print map(hex,a) # We can see the bytes being swapped It will produce the following output − Our array is: [1 256 8755] Representation of data in memory in hexadecimal form: [”0x1”, ”0x100”, ”0x2233”] Applying byteswap() function: [256 1 13090] In hexadecimal form: [”0x100”, ”0x1”, ”0x3322”] Print Page Previous Next Advertisements ”;
NumPy – Arithmetic Operations ”; Previous Next Input arrays for performing arithmetic operations such as add(), subtract(), multiply(), and divide() must be either of the same shape or should conform to array broadcasting rules. Example Live Demo import numpy as np a = np.arange(9, dtype = np.float_).reshape(3,3) print ”First array:” print a print ”n” print ”Second array:” b = np.array([10,10,10]) print b print ”n” print ”Add the two arrays:” print np.add(a,b) print ”n” print ”Subtract the two arrays:” print np.subtract(a,b) print ”n” print ”Multiply the two arrays:” print np.multiply(a,b) print ”n” print ”Divide the two arrays:” print np.divide(a,b) It will produce the following output − First array: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] Second array: [10 10 10] Add the two arrays: [[ 10. 11. 12.] [ 13. 14. 15.] [ 16. 17. 18.]] Subtract the two arrays: [[-10. -9. -8.] [ -7. -6. -5.] [ -4. -3. -2.]] Multiply the two arrays: [[ 0. 10. 20.] [ 30. 40. 50.] [ 60. 70. 80.]] Divide the two arrays: [[ 0. 0.1 0.2] [ 0.3 0.4 0.5] [ 0.6 0.7 0.8]] Let us now discuss some of the other important arithmetic functions available in NumPy. numpy.reciprocal() This function returns the reciprocal of argument, element-wise. For elements with absolute values larger than 1, the result is always 0 because of the way in which Python handles integer division. For integer 0, an overflow warning is issued. Example Live Demo import numpy as np a = np.array([0.25, 1.33, 1, 0, 100]) print ”Our array is:” print a print ”n” print ”After applying reciprocal function:” print np.reciprocal(a) print ”n” b = np.array([100], dtype = int) print ”The second array is:” print b print ”n” print ”After applying reciprocal function:” print np.reciprocal(b) It will produce the following output − Our array is: [ 0.25 1.33 1. 0. 100. ] After applying reciprocal function: main.py:9: RuntimeWarning: divide by zero encountered in reciprocal print np.reciprocal(a) [ 4. 0.7518797 1. inf 0.01 ] The second array is: [100] After applying reciprocal function: [0] numpy.power() This function treats elements in the first input array as base and returns it raised to the power of the corresponding element in the second input array. Live Demo import numpy as np a = np.array([10,100,1000]) print ”Our array is:” print a print ”n” print ”Applying power function:” print np.power(a,2) print ”n” print ”Second array:” b = np.array([1,2,3]) print b print ”n” print ”Applying power function again:” print np.power(a,b) It will produce the following output − Our array is: [ 10 100 1000] Applying power function: [ 100 10000 1000000] Second array: [1 2 3] Applying power function again: [ 10 10000 1000000000] numpy.mod() This function returns the remainder of division of the corresponding elements in the input array. The function numpy.remainder() also produces the same result. Live Demo import numpy as np a = np.array([10,20,30]) b = np.array([3,5,7]) print ”First array:” print a print ”n” print ”Second array:” print b print ”n” print ”Applying mod() function:” print np.mod(a,b) print ”n” print ”Applying remainder() function:” print np.remainder(a,b) It will produce the following output − First array: [10 20 30] Second array: [3 5 7] Applying mod() function: [1 0 2] Applying remainder() function: [1 0 2] The following functions are used to perform operations on array with complex numbers. numpy.real() − returns the real part of the complex data type argument. numpy.imag() − returns the imaginary part of the complex data type argument. numpy.conj() − returns the complex conjugate, which is obtained by changing the sign of the imaginary part. numpy.angle() − returns the angle of the complex argument. The function has degree parameter. If true, the angle in the degree is returned, otherwise the angle is in radians. Live Demo import numpy as np a = np.array([-5.6j, 0.2j, 11. , 1+1j]) print ”Our array is:” print a print ”n” print ”Applying real() function:” print np.real(a) print ”n” print ”Applying imag() function:” print np.imag(a) print ”n” print ”Applying conj() function:” print np.conj(a) print ”n” print ”Applying angle() function:” print np.angle(a) print ”n” print ”Applying angle() function again (result in degrees)” print np.angle(a, deg = True) It will produce the following output − Our array is: [ 0.-5.6j 0.+0.2j 11.+0.j 1.+1.j ] Applying real() function: [ 0. 0. 11. 1.] Applying imag() function: [-5.6 0.2 0. 1. ] Applying conj() function: [ 0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ] Applying angle() function: [-1.57079633 1.57079633 0. 0.78539816] Applying angle() function again (result in degrees) [-90. 90. 0. 45.] Print Page Previous Next Advertisements ”;
NumPy – Indexing & Slicing
NumPy – Indexing & Slicing ”; Previous Next Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python”s in-built container objects. As mentioned earlier, items in ndarray object follows zero-based index. Three types of indexing methods are available − field access, basic slicing and advanced indexing. Basic slicing is an extension of Python”s basic concept of slicing to n dimensions. A Python slice object is constructed by giving start, stop, and step parameters to the built-in slice function. This slice object is passed to the array to extract a part of array. Example 1 Live Demo import numpy as np a = np.arange(10) s = slice(2,7,2) print a[s] Its output is as follows − [2 4 6] In the above example, an ndarray object is prepared by arange() function. Then a slice object is defined with start, stop, and step values 2, 7, and 2 respectively. When this slice object is passed to the ndarray, a part of it starting with index 2 up to 7 with a step of 2 is sliced. The same result can also be obtained by giving the slicing parameters separated by a colon : (start:stop:step) directly to the ndarray object. Example 2 Live Demo import numpy as np a = np.arange(10) b = a[2:7:2] print b Here, we will get the same output − [2 4 6] If only one parameter is put, a single item corresponding to the index will be returned. If a : is inserted in front of it, all items from that index onwards will be extracted. If two parameters (with : between them) is used, items between the two indexes (not including the stop index) with default step one are sliced. Example 3 Live Demo # slice single item import numpy as np a = np.arange(10) b = a[5] print b Its output is as follows − 5 Example 4 Live Demo # slice items starting from index import numpy as np a = np.arange(10) print a[2:] Now, the output would be − [2 3 4 5 6 7 8 9] Example 5 Live Demo # slice items between indexes import numpy as np a = np.arange(10) print a[2:5] Here, the output would be − [2 3 4] The above description applies to multi-dimensional ndarray too. Example 6 Live Demo import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print a # slice items starting from index print ”Now we will slice the array from the index a[1:]” print a[1:] The output is as follows − [[1 2 3] [3 4 5] [4 5 6]] Now we will slice the array from the index a[1:] [[3 4 5] [4 5 6]] Slicing can also include ellipsis (…) to make a selection tuple of the same length as the dimension of an array. If ellipsis is used at the row position, it will return an ndarray comprising of items in rows. Example 7 Live Demo # array to begin with import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print ”Our array is:” print a print ”n” # this returns array of items in the second column print ”The items in the second column are:” print a[…,1] print ”n” # Now we will slice all items from the second row print ”The items in the second row are:” print a[1,…] print ”n” # Now we will slice all items from column 1 onwards print ”The items column 1 onwards are:” print a[…,1:] The output of this program is as follows − Our array is: [[1 2 3] [3 4 5] [4 5 6]] The items in the second column are: [2 4 5] The items in the second row are: [3 4 5] The items column 1 onwards are: [[2 3] [4 5] [5 6]] Print Page Previous Next Advertisements ”;
NumPy – Iterating Over Array
NumPy – Iterating Over Array ”; Previous Next NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface. Let us create a 3X4 array using arange() function and iterate over it using nditer. Example 1 Live Demo import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print ”Original array is:” print a print ”n” print ”Modified array is:” for x in np.nditer(a): print x, The output of this program is as follows − Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Modified array is: 0 5 10 15 20 25 30 35 40 45 50 55 Example 2 The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array. Live Demo import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print ”Original array is:” print a print ”n” print ”Transpose of the original array is:” b = a.T print b print ”n” print ”Modified array is:” for x in np.nditer(b): print x, The output of the above program is as follows − Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Transpose of the original array is: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] Modified array is: 0 5 10 15 20 25 30 35 40 45 50 55 Iteration Order If the same elements are stored using F-style order, the iterator chooses the more efficient way of iterating over an array. Example 1 Live Demo import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print ”Original array is:” print a print ”n” print ”Transpose of the original array is:” b = a.T print b print ”n” print ”Sorted in C-style order:” c = b.copy(order = ”C”) print c for x in np.nditer(c): print x, print ”n” print ”Sorted in F-style order:” c = b.copy(order = ”F”) print c for x in np.nditer(c): print x, Its output would be as follows − Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Transpose of the original array is: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] Sorted in C-style order: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] 0 20 40 5 25 45 10 30 50 15 35 55 Sorted in F-style order: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] 0 5 10 15 20 25 30 35 40 45 50 55 Example 2 It is possible to force nditer object to use a specific order by explicitly mentioning it. Live Demo import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print ”Original array is:” print a print ”n” print ”Sorted in C-style order:” for x in np.nditer(a, order = ”C”): print x, print ”n” print ”Sorted in F-style order:” for x in np.nditer(a, order = ”F”): print x, Its output would be − Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Sorted in C-style order: 0 5 10 15 20 25 30 35 40 45 50 55 Sorted in F-style order: 0 20 40 5 25 45 10 30 50 15 35 55 Modifying Array Values The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator. Example Live Demo import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print ”Original array is:” print a print ”n” for x in np.nditer(a, op_flags = [”readwrite”]): x[…] = 2*x print ”Modified array is:” print a Its output is as follows − Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Modified array is: [[ 0 10 20 30] [ 40 50 60 70] [ 80 90 100 110]] External Loop The nditer class constructor has a ‘flags’ parameter, which can take the following values − Sr.No. Parameter & Description 1 c_index C_order index can be tracked 2 f_index Fortran_order index is tracked 3 multi-index Type of indexes with one per iteration can be tracked 4 external_loop Causes values given to be one-dimensional arrays with multiple values instead of zero-dimensional array Example In the following example, one-dimensional arrays corresponding to each column is traversed by the iterator. Live Demo import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print ”Original array is:” print a print ”n” print ”Modified array is:” for x in np.nditer(a, flags = [”external_loop”], order = ”F”): print x, The output is as follows − Original array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Modified array is: [ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55] Broadcasting Iteration If two arrays are broadcastable, a combined nditer object is able to iterate upon them concurrently. Assuming that an array a has dimension 3X4, and there is another array b of dimension 1X4, the iterator of following type is used (array b is broadcast to size of a). Example Live Demo import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print ”First array is:” print a print ”n” print ”Second array is:” b = np.array([1, 2, 3, 4], dtype = int) print b print ”n” print ”Modified array is:” for x,y in np.nditer([a,b]): print “%d:%d” % (x,y), Its output would be as follows − First array is: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] Second array is: [1 2 3 4] Modified array is: 0:1 5:2 10:3 15:4 20:1 25:2 30:3
Array From Numerical Ranges
NumPy – Array From Numerical Ranges ”; Previous Next In this chapter, we will see how to create an array from numerical ranges. numpy.arange This function returns an ndarray object containing evenly spaced values within a given range. The format of the function is as follows − numpy.arange(start, stop, step, dtype) The constructor takes the following parameters. Sr.No. Parameter & Description 1 start The start of an interval. If omitted, defaults to 0 2 stop The end of an interval (not including this number) 3 step Spacing between values, default is 1 4 dtype Data type of resulting ndarray. If not given, data type of input is used The following examples show how you can use this function. Example 1 Live Demo import numpy as np x = np.arange(5) print x Its output would be as follows − [0 1 2 3 4] Example 2 Live Demo import numpy as np # dtype set x = np.arange(5, dtype = float) print x Here, the output would be − [0. 1. 2. 3. 4.] Example 3 Live Demo # start and stop parameters set import numpy as np x = np.arange(10,20,2) print x Its output is as follows − [10 12 14 16 18] numpy.linspace This function is similar to arange() function. In this function, instead of step size, the number of evenly spaced values between the interval is specified. The usage of this function is as follows − numpy.linspace(start, stop, num, endpoint, retstep, dtype) The constructor takes the following parameters. Sr.No. Parameter & Description 1 start The starting value of the sequence 2 stop The end value of the sequence, included in the sequence if endpoint set to true 3 num The number of evenly spaced samples to be generated. Default is 50 4 endpoint True by default, hence the stop value is included in the sequence. If false, it is not included 5 retstep If true, returns samples and step between the consecutive numbers 6 dtype Data type of output ndarray The following examples demonstrate the use linspace function. Example 1 Live Demo import numpy as np x = np.linspace(10,20,5) print x Its output would be − [10. 12.5 15. 17.5 20.] Example 2 Live Demo # endpoint set to false import numpy as np x = np.linspace(10,20, 5, endpoint = False) print x The output would be − [10. 12. 14. 16. 18.] Example 3 Live Demo # find retstep value import numpy as np x = np.linspace(1,2,5, retstep = True) print x # retstep here is 0.25 Now, the output would be − (array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25) numpy.logspace This function returns an ndarray object that contains the numbers that are evenly spaced on a log scale. Start and stop endpoints of the scale are indices of the base, usually 10. numpy.logspace(start, stop, num, endpoint, base, dtype) Following parameters determine the output of logspace function. Sr.No. Parameter & Description 1 start The starting point of the sequence is basestart 2 stop The final value of sequence is basestop 3 num The number of values between the range. Default is 50 4 endpoint If true, stop is the last value in the range 5 base Base of log space, default is 10 6 dtype Data type of output array. If not given, it depends upon other input arguments The following examples will help you understand the logspace function. Example 1 Live Demo import numpy as np # default base is 10 a = np.logspace(1.0, 2.0, num = 10) print a Its output would be as follows − [ 10. 12.91549665 16.68100537 21.5443469 27.82559402 35.93813664 46.41588834 59.94842503 77.42636827 100. ] Example 2 Live Demo # set base of log space to 2 import numpy as np a = np.logspace(1,10,num = 10, base = 2) print a Now, the output would be − [ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.] Print Page Previous Next Advertisements ”;
NumPy – Matrix Library
NumPy – Matrix Library ”; Previous Next NumPy package contains a Matrix library numpy.matlib. This module has functions that return matrices instead of ndarray objects. matlib.empty() The matlib.empty() function returns a new matrix without initializing the entries. The function takes the following parameters. numpy.matlib.empty(shape, dtype, order) Where, Sr.No. Parameter & Description 1 shape int or tuple of int defining the shape of the new matrix 2 Dtype Optional. Data type of the output 3 order C or F Example Live Demo import numpy.matlib import numpy as np print np.matlib.empty((2,2)) # filled with random data It will produce the following output − [[ 2.12199579e-314, 4.24399158e-314] [ 4.24399158e-314, 2.12199579e-314]] numpy.matlib.zeros() This function returns the matrix filled with zeros. Live Demo import numpy.matlib import numpy as np print np.matlib.zeros((2,2)) It will produce the following output − [[ 0. 0.] [ 0. 0.]] numpy.matlib.ones() This function returns the matrix filled with 1s. Live Demo import numpy.matlib import numpy as np print np.matlib.ones((2,2)) It will produce the following output − [[ 1. 1.] [ 1. 1.]] numpy.matlib.eye() This function returns a matrix with 1 along the diagonal elements and the zeros elsewhere. The function takes the following parameters. numpy.matlib.eye(n, M,k, dtype) Where, Sr.No. Parameter & Description 1 n The number of rows in the resulting matrix 2 M The number of columns, defaults to n 3 k Index of diagonal 4 dtype Data type of the output Example Live Demo import numpy.matlib import numpy as np print np.matlib.eye(n = 3, M = 4, k = 0, dtype = float) It will produce the following output − [[ 1. 0. 0. 0.] [ 0. 1. 0. 0.] [ 0. 0. 1. 0.]] numpy.matlib.identity() The numpy.matlib.identity() function returns the Identity matrix of the given size. An identity matrix is a square matrix with all diagonal elements as 1. Live Demo import numpy.matlib import numpy as np print np.matlib.identity(5, dtype = float) It will produce the following output − [[ 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.]] numpy.matlib.rand() The numpy.matlib.rand() function returns a matrix of the given size filled with random values. Example Live Demo import numpy.matlib import numpy as np print np.matlib.rand(3,3) It will produce the following output − [[ 0.82674464 0.57206837 0.15497519] [ 0.33857374 0.35742401 0.90895076] [ 0.03968467 0.13962089 0.39665201]] Note that a matrix is always two-dimensional, whereas ndarray is an n-dimensional array. Both the objects are inter-convertible. Example Live Demo import numpy.matlib import numpy as np i = np.matrix(”1,2;3,4”) print i It will produce the following output − [[1 2] [3 4]] Example import numpy.matlib import numpy as np j = np.asarray(i) print j It will produce the following output − [[1 2] [3 4]] Example import numpy.matlib import numpy as np k = np.asmatrix (j) print k It will produce the following output − [[1 2] [3 4]] Print Page Previous Next Advertisements ”;