NumPy – Matplotlib ”; Previous Next Matplotlib is a plotting library for Python. It is used along with NumPy to provide an environment that is an effective open source alternative for MatLab. It can also be used with graphics toolkits like PyQt and wxPython. Matplotlib module was first written by John D. Hunter. Since 2012, Michael Droettboom is the principal developer. Currently, Matplotlib ver. 1.5.1 is the stable version available. The package is available in binary distribution as well as in the source code form on www.matplotlib.org. Conventionally, the package is imported into the Python script by adding the following statement − from matplotlib import pyplot as plt Here pyplot() is the most important function in matplotlib library, which is used to plot 2D data. The following script plots the equation y = 2x + 5 Example import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title(“Matplotlib demo”) plt.xlabel(“x axis caption”) plt.ylabel(“y axis caption”) plt.plot(x,y) plt.show() An ndarray object x is created from np.arange() function as the values on the x axis. The corresponding values on the y axis are stored in another ndarray object y. These values are plotted using plot() function of pyplot submodule of matplotlib package. The graphical representation is displayed by show() function. The above code should produce the following output − Instead of the linear graph, the values can be displayed discretely by adding a format string to the plot() function. Following formatting characters can be used. Sr.No. Character & Description 1 ”-” Solid line style 2 ”–” Dashed line style 3 ”-.” Dash-dot line style 4 ”:” Dotted line style 5 ”.” Point marker 6 ”,” Pixel marker 7 ”o” Circle marker 8 ”v” Triangle_down marker 9 ”^” Triangle_up marker 10 ”<” Triangle_left marker 11 ”>” Triangle_right marker 12 ”1” Tri_down marker 13 ”2” Tri_up marker 14 ”3” Tri_left marker 15 ”4” Tri_right marker 16 ”s” Square marker 17 ”p” Pentagon marker 18 ”*” Star marker 19 ”h” Hexagon1 marker 20 ”H” Hexagon2 marker 21 ”+” Plus marker 22 ”x” X marker 23 ”D” Diamond marker 24 ”d” Thin_diamond marker 25 ”|” Vline marker 26 ”_” Hline marker The following color abbreviations are also defined. Character Color ”b” Blue ”g” Green ”r” Red ”c” Cyan ”m” Magenta ”y” Yellow ”k” Black ”w” White To display the circles representing points, instead of the line in the above example, use “ob” as the format string in plot() function. Example import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title(“Matplotlib demo”) plt.xlabel(“x axis caption”) plt.ylabel(“y axis caption”) plt.plot(x,y,”ob”) plt.show() The above code should produce the following output − Sine Wave Plot The following script produces the sine wave plot using matplotlib. Example import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on a sine curve x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) plt.title(“sine wave form”) # Plot the points using matplotlib plt.plot(x, y) plt.show() subplot() The subplot() function allows you to plot different things in the same figure. In the following script, sine and cosine values are plotted. Example import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on sine and cosine curves x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # Set up a subplot grid that has height 2 and width 1, # and set the first such subplot as active. plt.subplot(2, 1, 1) # Make the first plot plt.plot(x, y_sin) plt.title(”Sine”) # Set the second subplot as active, and make the second plot. plt.subplot(2, 1, 2) plt.plot(x, y_cos) plt.title(”Cosine”) # Show the figure. plt.show() The above code should produce the following output − bar() The pyplot submodule provides bar() function to generate bar graphs. The following example produces the bar graph of two sets of x and y arrays. Example from matplotlib import pyplot as plt x = [5,8,10] y = [12,16,6] x2 = [6,9,11] y2 = [6,15,7] plt.bar(x, y, align = ”center”) plt.bar(x2, y2, color = ”g”, align = ”center”) plt.title(”Bar graph”) plt.ylabel(”Y axis”) plt.xlabel(”X axis”) plt.show() This code should produce the following output − Print Page Previous Next Advertisements ”;
Category: numpy
NumPy – Linear Algebra
NumPy – Linear Algebra ”; Previous Next NumPy package contains numpy.linalg module that provides all the functionality required for linear algebra. Some of the important functions in this module are described in the following table. Sr.No. Function & Description 1 dot Dot product of the two arrays 2 vdot Dot product of the two vectors 3 inner Inner product of the two arrays 4 matmul Matrix product of the two arrays 5 determinant Computes the determinant of the array 6 solve Solves the linear matrix equation 7 inv Finds the multiplicative inverse of the matrix Print Page Previous Next Advertisements ”;
NumPy – Useful Resources
NumPy – Useful Resources ”; Previous Next The following resources contain additional information on NumPy. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Python Data Science Course With Numpy, Pandas, and Matplotlib Best Seller 64 Lectures 6 hours Abhilash Nelson More Detail Data Analysis using NumPy and Pandas 20 Lectures 8 hours DATAhill Solutions Srinivas Reddy More Detail Numpy Full Python Course Most Popular 13 Lectures 3 hours DATAhill Solutions Srinivas Reddy More Detail Basics Data Science with Numpy, Pandas and Matplotlib 11 Lectures 2.5 hours Akbar Khan More Detail NumPy For Data Science & Machine Learning: From Beginner To Advanced 21 Lectures 2 hours Pruthviraja L – Team UpGraduate More Detail Pandas Crash Course for beginners : NumPy + Pandas + Matplotlib Most Popular 63 Lectures 6 hours Anmol Tomar More Detail Print Page Previous Next Advertisements ”;
NumPy – Sort, Search & Counting Functions ”; Previous Next A variety of sorting related functions are available in NumPy. These sorting functions implement different sorting algorithms, each of them characterized by the speed of execution, worst case performance, the workspace required and the stability of algorithms. Following table shows the comparison of three sorting algorithms. kind speed worst case work space stable ‘quicksort’ 1 O(n^2) 0 no ‘mergesort’ 2 O(n*log(n)) ~n/2 yes ‘heapsort’ 3 O(n*log(n)) 0 no numpy.sort() The sort() function returns a sorted copy of the input array. It has the following parameters − numpy.sort(a, axis, kind, order) Where, Sr.No. Parameter & Description 1 a Array to be sorted 2 axis The axis along which the array is to be sorted. If none, the array is flattened, sorting on the last axis 3 kind Default is quicksort 4 order If the array contains fields, the order of fields to be sorted Example Live Demo import numpy as np a = np.array([[3,7],[9,1]]) print ”Our array is:” print a print ”n” print ”Applying sort() function:” print np.sort(a) print ”n” print ”Sort along axis 0:” print np.sort(a, axis = 0) print ”n” # Order parameter in sort function dt = np.dtype([(”name”, ”S10”),(”age”, int)]) a = np.array([(“raju”,21),(“anil”,25),(“ravi”, 17), (“amar”,27)], dtype = dt) print ”Our array is:” print a print ”n” print ”Order by name:” print np.sort(a, order = ”name”) It will produce the following output − Our array is: [[3 7] [9 1]] Applying sort() function: [[3 7] [1 9]] Sort along axis 0: [[3 1] [9 7]] Our array is: [(”raju”, 21) (”anil”, 25) (”ravi”, 17) (”amar”, 27)] Order by name: [(”amar”, 27) (”anil”, 25) (”raju”, 21) (”ravi”, 17)] numpy.argsort() The numpy.argsort() function performs an indirect sort on input array, along the given axis and using a specified kind of sort to return the array of indices of data. This indices array is used to construct the sorted array. Example Live Demo import numpy as np x = np.array([3, 1, 2]) print ”Our array is:” print x print ”n” print ”Applying argsort() to x:” y = np.argsort(x) print y print ”n” print ”Reconstruct original array in sorted order:” print x[y] print ”n” print ”Reconstruct the original array using loop:” for i in y: print x[i], It will produce the following output − Our array is: [3 1 2] Applying argsort() to x: [1 2 0] Reconstruct original array in sorted order: [1 2 3] Reconstruct the original array using loop: 1 2 3 numpy.lexsort() function performs an indirect sort using a sequence of keys. The keys can be seen as a column in a spreadsheet. The function returns an array of indices, using which the sorted data can be obtained. Note, that the last key happens to be the primary key of sort. Example Live Demo import numpy as np nm = (”raju”,”anil”,”ravi”,”amar”) dv = (”f.y.”, ”s.y.”, ”s.y.”, ”f.y.”) ind = np.lexsort((dv,nm)) print ”Applying lexsort() function:” print ind print ”n” print ”Use this index to get sorted data:” print [nm[i] + “, ” + dv[i] for i in ind] It will produce the following output − Applying lexsort() function: [3 1 0 2] Use this index to get sorted data: [”amar, f.y.”, ”anil, s.y.”, ”raju, f.y.”, ”ravi, s.y.”] NumPy module has a number of functions for searching inside an array. Functions for finding the maximum, the minimum as well as the elements satisfying a given condition are available. numpy.argmax() and numpy.argmin() These two functions return the indices of maximum and minimum elements respectively along the given axis. Example Live Demo import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]]) print ”Our array is:” print a print ”n” print ”Applying argmax() function:” print np.argmax(a) print ”n” print ”Index of maximum number in flattened array” print a.flatten() print ”n” print ”Array containing indices of maximum along axis 0:” maxindex = np.argmax(a, axis = 0) print maxindex print ”n” print ”Array containing indices of maximum along axis 1:” maxindex = np.argmax(a, axis = 1) print maxindex print ”n” print ”Applying argmin() function:” minindex = np.argmin(a) print minindex print ”n” print ”Flattened array:” print a.flatten()[minindex] print ”n” print ”Flattened array along axis 0:” minindex = np.argmin(a, axis = 0) print minindex print ”n” print ”Flattened array along axis 1:” minindex = np.argmin(a, axis = 1) print minindex It will produce the following output − Our array is: [[30 40 70] [80 20 10] [50 90 60]] Applying argmax() function: 7 Index of maximum number in flattened array [30 40 70 80 20 10 50 90 60] Array containing indices of maximum along axis 0: [1 2 0] Array containing indices of maximum along axis 1: [2 0 1] Applying argmin() function: 5 Flattened array: 10 Flattened array along axis 0: [0 1 1] Flattened array along axis 1: [0 2 0] numpy.nonzero() The numpy.nonzero() function returns the indices of non-zero elements in the input array. Example Live Demo import numpy as np a = np.array([[30,40,0],[0,20,10],[50,0,60]]) print ”Our array is:” print a print ”n” print ”Applying nonzero() function:” print np.nonzero (a) It will produce the following output − Our array is: [[30 40 0] [ 0 20 10] [50 0 60]] Applying nonzero() function: (array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2])) numpy.where() The where() function returns the indices of elements in an input array where the given condition is satisfied. Example Live Demo import numpy as np x = np.arange(9.).reshape(3, 3) print ”Our array is:” print x print ”Indices of elements > 3” y = np.where(x > 3) print y print ”Use these indices to get elements satisfying the condition” print x[y] It will produce the following output − Our array is: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] Indices of elements > 3 (array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2])) Use these indices to get elements satisfying the condition [ 4. 5. 6. 7. 8.] numpy.extract() The extract() function returns the elements satisfying any condition. Live Demo import numpy as
NumPy – Quick Guide
NumPy – Quick Guide ”; Previous Next NumPy – Introduction NumPy is a Python package. It stands for ”Numerical Python”. It is a library consisting of multidimensional array objects and a collection of routines for processing of array. Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray was also developed, having some additional functionalities. In 2005, Travis Oliphant created NumPy package by incorporating the features of Numarray into Numeric package. There are many contributors to this open source project. Operations using NumPy Using NumPy, a developer can perform the following operations − Mathematical and logical operations on arrays. Fourier transforms and routines for shape manipulation. Operations related to linear algebra. NumPy has in-built functions for linear algebra and random number generation. NumPy – A Replacement for MatLab NumPy is often used along with packages like SciPy (Scientific Python) and Mat−plotlib (plotting library). This combination is widely used as a replacement for MatLab, a popular platform for technical computing. However, Python alternative to MatLab is now seen as a more modern and complete programming language. It is open source, which is an added advantage of NumPy. NumPy – Environment 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 NumPy – Ndarray Object The most important object defined in NumPy is an N-dimensional array type called ndarray. It describes the collection of items of the same type. Items in the collection can be accessed using a zero-based index. Every item in an ndarray takes the same size of block in the memory. Each element in ndarray is an object of data-type object (called dtype). Any item extracted from ndarray object (by slicing) is represented by a Python object of one of array scalar types. The following diagram shows a relationship between ndarray, data type object (dtype) and array scalar type − An instance of ndarray class can be constructed by different array creation routines described later in the tutorial. The basic ndarray is created using an array function in NumPy as follows − numpy.array It creates an ndarray from any object exposing array interface, or from any method that returns an array. numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0) The above constructor takes the following parameters − Sr.No. Parameter & Description 1 object Any object exposing the array interface method returns an array, or any (nested) sequence. 2 dtype Desired data type of array, optional 3 copy Optional. By default (true), the object is copied 4 order C (row major) or F (column major) or A (any) (default) 5 subok By default, returned array forced to be a base class array. If true, sub-classes passed through 6 ndmin Specifies minimum dimensions of resultant array Take a look at the following examples to understand better. Example 1 Live Demo import numpy as np a = np.array([1,2,3]) print a The output is as follows − [1, 2, 3] Example 2 Live Demo # more than one dimensions import numpy as np a = np.array([[1, 2], [3, 4]]) print a The output is as follows − [[1, 2] [3, 4]] Example 3 Live Demo # minimum dimensions import numpy as np a = np.array([1, 2, 3,4,5], ndmin = 2) print a The output is as follows − [[1, 2, 3, 4, 5]] Example 4 Live Demo # dtype parameter import numpy as np a = np.array([1, 2, 3], dtype = complex) print a The output is as follows − [ 1.+0.j, 2.+0.j, 3.+0.j] The ndarray object consists of contiguous one-dimensional segment of computer memory, combined with an indexing scheme that maps each item to a location in the memory block. The memory block holds the elements in a row-major order (C style) or a column-major order (FORTRAN or MatLab style). NumPy – Data Types NumPy supports a much greater variety of numerical types than Python does. The following table shows different scalar data types defined in NumPy. Sr.No. Data Types & Description 1 bool_ Boolean (True or False) stored as a byte 2 int_ Default integer type (same as C long; normally either int64 or int32) 3 intc Identical to C int (normally int32 or int64) 4 intp Integer used for indexing (same as C ssize_t; normally either int32 or int64) 5 int8 Byte (-128 to 127) 6 int16 Integer (-32768 to 32767) 7 int32 Integer (-2147483648 to 2147483647) 8 int64 Integer (-9223372036854775808 to 9223372036854775807) 9 uint8 Unsigned integer (0 to 255)
NumPy – Copies & Views
NumPy – Copies & Views ”; Previous Next While executing the functions, some of them return a copy of the input array, while some return the view. When the contents are physically stored in another location, it is called Copy. If on the other hand, a different view of the same memory content is provided, we call it as View. No Copy Simple assignments do not make the copy of array object. Instead, it uses the same id() of the original array to access it. The id() returns a universal identifier of Python object, similar to the pointer in C. Furthermore, any changes in either gets reflected in the other. For example, the changing shape of one will change the shape of the other too. Example Live Demo import numpy as np a = np.arange(6) print ”Our array is:” print a print ”Applying id() function:” print id(a) print ”a is assigned to b:” b = a print b print ”b has same id():” print id(b) print ”Change shape of b:” b.shape = 3,2 print b print ”Shape of a also gets changed:” print a It will produce the following output − Our array is: [0 1 2 3 4 5] Applying id() function: 139747815479536 a is assigned to b: [0 1 2 3 4 5] b has same id(): 139747815479536 Change shape of b: [[0 1] [2 3] [4 5]] Shape of a also gets changed: [[0 1] [2 3] [4 5]] View or Shallow Copy NumPy has ndarray.view() method which is a new array object that looks at the same data of the original array. Unlike the earlier case, change in dimensions of the new array doesn’t change dimensions of the original. Example Live Demo import numpy as np # To begin with, a is 3X2 array a = np.arange(6).reshape(3,2) print ”Array a:” print a print ”Create view of a:” b = a.view() print b print ”id() for both the arrays are different:” print ”id() of a:” print id(a) print ”id() of b:” print id(b) # Change the shape of b. It does not change the shape of a b.shape = 2,3 print ”Shape of b:” print b print ”Shape of a:” print a It will produce the following output − Array a: [[0 1] [2 3] [4 5]] Create view of a: [[0 1] [2 3] [4 5]] id() for both the arrays are different: id() of a: 140424307227264 id() of b: 140424151696288 Shape of b: [[0 1 2] [3 4 5]] Shape of a: [[0 1] [2 3] [4 5]] Slice of an array creates a view. Example Live Demo import numpy as np a = np.array([[10,10], [2,3], [4,5]]) print ”Our array is:” print a print ”Create a slice:” s = a[:, :2] print s It will produce the following output − Our array is: [[10 10] [ 2 3] [ 4 5]] Create a slice: [[10 10] [ 2 3] [ 4 5]] Deep Copy The ndarray.copy() function creates a deep copy. It is a complete copy of the array and its data, and doesn’t share with the original array. Example Live Demo import numpy as np a = np.array([[10,10], [2,3], [4,5]]) print ”Array a is:” print a print ”Create a deep copy of a:” b = a.copy() print ”Array b is:” print b #b does not share any memory of a print ”Can we write b is a” print b is a print ”Change the contents of b:” b[0,0] = 100 print ”Modified array b:” print b print ”a remains unchanged:” print a It will produce the following output − Array a is: [[10 10] [ 2 3] [ 4 5]] Create a deep copy of a: Array b is: [[10 10] [ 2 3] [ 4 5]] Can we write b is a False Change the contents of b: Modified array b: [[100 10] [ 2 3] [ 4 5]] a remains unchanged: [[10 10] [ 2 3] [ 4 5]] Print Page Previous Next Advertisements ”;
NumPy – I/O with NumPy
I/O with NumPy ”; Previous Next The ndarray objects can be saved to and loaded from the disk files. The IO functions available are − load() and save() functions handle /numPy binary files (with npy extension) loadtxt() and savetxt() functions handle normal text files NumPy introduces a simple file format for ndarray objects. This .npy file stores data, shape, dtype and other information required to reconstruct the ndarray in a disk file such that the array is correctly retrieved even if the file is on another machine with different architecture. numpy.save() The numpy.save() file stores the input array in a disk file with npy extension. import numpy as np a = np.array([1,2,3,4,5]) np.save(”outfile”,a) To reconstruct array from outfile.npy, use load() function. import numpy as np b = np.load(”outfile.npy”) print b It will produce the following output − array([1, 2, 3, 4, 5]) The save() and load() functions accept an additional Boolean parameter allow_pickles. A pickle in Python is used to serialize and de-serialize objects before saving to or reading from a disk file. savetxt() The storage and retrieval of array data in simple text file format is done with savetxt() and loadtxt() functions. Example import numpy as np a = np.array([1,2,3,4,5]) np.savetxt(”out.txt”,a) b = np.loadtxt(”out.txt”) print b It will produce the following output − [ 1. 2. 3. 4. 5.] The savetxt() and loadtxt() functions accept additional optional parameters such as header, footer, and delimiter. Print Page Previous Next Advertisements ”;
NumPy – Binary Operators
NumPy – Binary Operators ”; Previous Next Following are the functions for bitwise operations available in NumPy package. Sr.No. Operation & Description 1 bitwise_and Computes bitwise AND operation of array elements 2 bitwise_or Computes bitwise OR operation of array elements 3 invert Computes bitwise NOT 4 left_shift Shifts bits of a binary representation to the left 5 right_shift Shifts bits of binary representation to the right 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 ”;