I am so in.God bless you for this. lahp: There are several ways to create arrays. For example, you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced from the type of the elements in the sequences. A frequent error consists in calling array with multiple numeric arguments, rather than providing a single list of numbers as an argument. array transforms sequences of sequences into two- dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on. The type of the array can also be explicitly specified at creation time: Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. The function zeros creates an array full of zeros, the function ones creates an array full of ones, and the function empty creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is float64 . To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists. When arange is used with floating point arguments, it is generally not possible to predict the number of elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the function linspace that receives as an argument the number of elements that we want, instead of the step: See also: array , zeros, zeros_like , ones , ones_like , empty , empty_like , arange, linspace, numpy.random.rand , numpy.random.randn , fromfunction, fromfile Printing Arrays When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout: the last axis is printed from left to right, the second-to-last is printed from top to bottom, the rest are also printed from top to bottom, with each slice separated from the next by an empty line. One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensionals as lists of matrices. See below to get more details on reshape . If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners: To disable this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions . Basic Operations Arithmetic operators on arrays apply elementwise . A new array is created and filled with the result. Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The matrix product can be performed using the @ operator (in python >=3.5) or the dot function or method: Some operations, such as += and *=, act in place to modify an existing array rather than create a new one. When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as upcasting). Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array: Universal Functions NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called “universal functions”( ufunc ). Within NumPy, these functions operate elementwise on an array, producing an array as output. See also: all , any , apply_along_axis , argmax, argmin , argsort, average , bincount , ceil, clip , conj , corrcoef , cov , cross, cumprod , cumsum , diff, dot, floor, inner , inv, lexsort, max , maximum , mean , median , min, minimum, nonzero , outer , prod, re , round, sort , std, sum , trace, transpose , var, vdot , vectorize , where Indexing, Slicing and Iterating One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences. Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas: When fewer indices are provided than the number of axes, the missing indices are considered complete slices : The expression within brackets in b[i] is treated as an i followed by as many instances of : as needed to represent the remaining axes. NumPy also allows you to write this using dots as b[i,...] . The dots ( ... ) represent as many colons as needed to produce a complete indexing tuple. For example, if x is an array with 5 axes, then x[1,2,...] is equivalent to x[1,2,:,:,:] , x[...,3] to x[:,:,:,:,3] and x[4,...,5,:] to x[4,:,:,5,:] . Iterating over multidimensional arrays is done with respect to the first axis: However, if one wants to perform an operation on each element in the array, one can use the flat attribute which is an iterator over all the elements of the array: See also: Indexing , Indexing (reference), newaxis, ndenumerate , indices Shape Manipulation Changing the shape of an array An array has a shape given by the number of elements along each axis: The shape of an array can be changed with various commands. Note that the following three commands all return a modified array, but do not change the original array: The order of the elements in the array resulting from ravel () is normally “C-style”, that is, the rightmost index “changes the fastest”, so the element after a[0,0] is a [0,1]. If the array is reshaped to some other shape, again the array is treated as “C-style”. NumPy normally creates arrays stored in this order, so ravel() will usually not need to copy its argument, but if the array was made by taking slices of another array or created with unusual options, it may need to be copied. The functions ravel() and reshape () can also be instructed, using an optional argument, to use FORTRAN-style arrays, in which the leftmost index changes the fastest. The reshape function returns its argument with a modified shape, whereas the ndarray.resize method modifies the array itself: If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated: See also: ndarray.shape , reshape , resize , ravel Stacking together different arrays Several arrays can be stacked together along different axes: The function column_stack stacks 1D arrays as columns into a 2D array. It is equivalent to hstack only for 2D arrays: On the other hand, the function row_stack is equivalent to vstack for any input arrays. In general, for arrays of with more than two dimensions, hstack stacks along their second axes, vstack stacks along their first axes, and concatenate allows for an optional arguments giving the number of the axis along which the concatenation should happen. Note In complex cases, r_ and c_ are useful for creating arrays by stacking numbers along one axis. They allow the use of range literals (“:”) When used with arrays as arguments, r_ and c_ are similar to vstack and hstack in their default behavior, but allow for an optional argument giving the number of the axis along which to concatenate. See also: hstack , vstack, column_stack, concatenate, c_ , r_ Splitting one array into several smaller ones Using hsplit, you can split an array along its horizontal axis, either by specifying the number of equally shaped arrays to return, or by specifying the columns after which the division should occur: vsplit splits along the vertical axis, and array_split allows one to specify along which axis to split. Copies and Views When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not. This is often a source of confusion for beginners. There are three cases: No Copy at All Simple assignments make no copy of array objects or of their data. Python passes mutable objects as references, so function calls make no copy. View or Shallow Copy Different array objects can share the same data. The view method creates a new array object that looks at the same data. Slicing an array returns a view of it: Deep Copy The copy method makes a complete copy of the array and its data. Functions and Methods Overview Here is a list of some useful NumPy functions and methods names ordered in categories. See Routines for the full list. Array Creation arange, array, copy , empty , empty_like , eye, fromfile , fromfunction , identity, linspace, logspace , mgrid , ogrid , ones , ones_like , r , zeros, zeros_like Conversions ndarray.astype , atleast_1d , atleast_2d , atleast_3d , mat Manipulations array_split , column_stack, concatenate , diagonal , dsplit, dstack , hsplit, hstack , ndarray.item , newaxis , ravel , repeat , reshape , resize , squeeze, swapaxes , take , transpose, vsplit , vstack Questions all , any , nonzero , where Ordering argmax, argmin , argsort , max , min, ptp , searchsorted , sort Operations choose , compress , cumprod , cumsum , inner , ndarray.fill , imag , prod, put , putmask , real, sum Basic Statistics cov , mean , std, var Basic Linear Algebra cross, dot , outer , linalg.svd , vdot Less Basic Broadcasting rules Broadcasting allows universal functions to deal in a meaningful way with inputs that do not have exactly the same shape. The first rule of broadcasting is that if all input arrays do not have the same number of dimensions, a “1” will be repeatedly prepended to the shapes of the smaller arrays until all the arrays have the same number of dimensions. The second rule of broadcasting ensures that arrays with a size of 1 along a particular dimension act as if they had the size of the array with the largest shape along that dimension. The value of the array element is assumed to be the same along that dimension for the “broadcast” array. After application of the broadcasting rules, the sizes of all arrays must match. More details can be found in Broadcasting. Fancy indexing and index tricks NumPy offers more indexing facilities than regular Python sequences. In addition to indexing by integers and slices, as we saw before, arrays can be indexed by arrays of integers and arrays of booleans. Indexing with Arrays of Indices When the indexed array a is multidimensional, a single array of indices refers to the first dimension of a. The following example shows this behavior by converting an image of labels into a color image using a palette. We can also give indexes for more than one dimension. The arrays of indices for each dimension must have the same shape. Naturally, we can put i and j in a sequence (say a list) and then do the indexing with the list. However, we can not do this by putting i and j into an array, because this array will be interpreted as indexing the first dimension of a. Another common use of indexing with arrays is the search of the maximum value of time-dependent series: You can also use indexing with arrays as a target to assign to: However, when the list of indices contains repetitions, the assignment is done several times, leaving behind the last value: This is reasonable enough, but watch out if you want to use Python’s += construct, as it may not do what you expect: Even though 0 occurs twice in the list of indices, the 0th element is only incremented once. This is because Python requires “a+=1” to be equivalent to “a = a + 1”. Indexing with Boolean Arrays When we index arrays with arrays of (integer) indices we are providing the list of indices to pick. With boolean indices the approach is different; we explicitly choose which items in the array we want and which ones we don’t. The most natural way one can think of for boolean indexing is to use boolean arrays that have the same shape as the original array: This property can be very useful in assignments: You can look at the following example to see how to use boolean indexing to generate an image of the Mandelbrot set : The second way of indexing with booleans is more similar to integer indexing; for each dimension of the array we give a 1D boolean array selecting the slices we want: Note that the length of the 1D boolean array must coincide with the length of the dimension (or axis) you want to slice. In the previous example, b1 has length 3 (the number of rows in a), and b2 (of length 4) is suitable to index the 2nd axis (columns) of a. The ix_() function The ix_ function can be used to combine different vectors so as to obtain the result for each n-uplet. For example, if you want to compute all the a+b*c for all the triplets taken from each of the vectors a, b and c: You could also implement the reduce as follows: and then use it as: The advantage of this version of reduce compared to the normal ufunc.reduce is that it makes use of the Broadcasting Rules in order to avoid creating an argument array the size of the output times the number of vectors. Indexing with strings See Structured arrays . Linear Algebra Work in progress. Basic linear algebra to be included here. Simple Array Operations See linalg.py in numpy folder for more. Tricks and Tips Here we give a list of short and useful tips. “Automatic” Reshaping To change the dimensions of an array, you can omit one of the sizes which will then be deduced automatically: Vector Stacking How do we construct a 2D array from a list of equally- sized row vectors? In MATLAB this is quite easy: if x and y are two vectors of the same length you only need do m=[x;y] . In NumPy this works via the functions column_stack , dstack , hstack and vstack , depending on the dimension in which the stacking is to be done. For example: The logic behind those functions in more than two dimensions can be strange. See also: NumPy for Matlab users Histograms The NumPy histogram function applied to an array returns a pair of vectors: the histogram of the array and the vector of bins. Beware: matplotlib also has a function to build histograms (called hist, as in Matlab) that differs from the one in NumPy. The main difference is that pylab.hist plots the histogram automatically, while numpy.histogram only generates the data. Further reading The Python tutorial NumPy Reference SciPy Tutorial SciPy Lecture Notes A matlab, R, IDL, NumPy/SciPy dictionary Table Of Contents Quickstart tutorial Prerequisites The Basics An example Array Creation Printing Arrays Basic Operations Universal Functions Indexing, Slicing and Iterating Shape Manipulation Changing the shape of an array Stacking together different arrays Splitting one array into several smaller ones Copies and Views No Copy at All View or Shallow Copy Deep Copy Functions and Methods Overview Less Basic Broadcasting rules Fancy indexing and index tricks Indexing with Arrays of Indices Indexing with Boolean Arrays The ix_() function Indexing with strings Linear Algebra Simple Array Operations Tricks and Tips “Automatic” Reshaping Vector Stacking Histograms Further reading Previous topic Installing NumPy Next topic NumPy basics Quick search search [[ 1. , 0., 0.], [ 0. , 1., 2.]] >>> import numpy as np >>> a = np .arange( 15 ).reshape( 3, 5) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) >>> a .shape (3, 5) >>> a .ndim 2 >>> a .dtype .name 'int64' >>> a .itemsize 8 >>> a .size 15 >>> type (a) <type 'numpy.ndarray'> >>> b = np .array([ 6, 7, 8 ]) >>> b array([6, 7, 8]) >>> type (b) <type 'numpy.ndarray'> >>> >>> import numpy as np >>> a = np .array([ 2, 3,4]) >>> a array([2, 3, 4]) >>> a .dtype dtype('int64') >>> b = np .array([ 1.2 , 3.5 , 5.1 ]) >>> b .dtype dtype('float64') >>> >>> a = np .array( 1,2 ,3,4) # WRONG >>> a = np .array([ 1, 2,3,4 ]) # RIGHT >>> >>> b = np .array([( 1.5 ,2, 3), ( 4,5,6 )]) >>> b array([[ 1.5, 2. , 3. ], [ 4. , 5. , 6. ]]) >>> >>> c = np .array( [ [ 1,2], [ 3, 4] ], dtype =complex ) >>> c array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]]) >>> >>> np .zeros( ( 3,4) ) array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) >>> np .ones( ( 2 ,3,4), dtype =np.int16 ) # dtype can also be specified array([[[ 1, 1, 1, 1], [ 1, 1, 1, 1], [ 1, 1, 1, 1]], [[ 1, 1, 1, 1], [ 1, 1, 1, 1], [ 1, 1, 1, 1]]], dtype=int16) >>> np .empty ( (2, 3) ) # uninitialized, output may vary array([[ 3.73603959e-262, 6.02658058e-154, 6.55490914e-260], [ 5.30498948e-313, 3.14673309e-307, 1.00000000e+000]]) >>> >>> np .arange( 10, 30 , 5 ) array([10, 15, 20, 25]) >>> np .arange( 0, 2, 0.3 ) # it accepts float arguments array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8]) >>> >>> from numpy import pi >>> np .linspace( 0 , 2, 9 ) # 9 numbers from 0 to 2 array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ]) >>> x = np .linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points >>> f = np .sin(x) |