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 – 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