doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.ndarray.mean method ndarray.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True) Returns the average of the array elements along given axis. Refer to numpy.mean for full documentation. See also numpy.mean equivalent function
numpy.reference.generated.numpy.ndarray.mean
numpy.ndarray.min method ndarray.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True) Return the minimum along a given axis. Refer to numpy.amin for full documentation. See also numpy.amin equivalent function
numpy.reference.generated.numpy.ndarray.min
numpy.ndarray.nbytes attribute ndarray.nbytes Total bytes consumed by the elements of the array. Notes Does not include memory consumed by non-element attributes of the array object. Examples >>> x = np.zeros((3,5,2), dtype=np.complex128) >>> x.nbytes 480 >>> np.prod(x.shape) * x.itemsize 480
numpy.reference.generated.numpy.ndarray.nbytes
numpy.ndarray.ndim attribute ndarray.ndim Number of array dimensions. Examples >>> x = np.array([1, 2, 3]) >>> x.ndim 1 >>> y = np.zeros((2, 3, 4)) >>> y.ndim 3
numpy.reference.generated.numpy.ndarray.ndim
NumPy quickstart Prerequisites You’ll need to know a bit of Python. For a refresher, see the Python tutorial. To work the examples, you’ll need matplotlib installed in addition to NumPy. Learner profile This is a quick overview of arrays in NumPy. It demonstrates how n-dimensional (\(n>=2\)) arrays are represented and can be manipulated. In particular, if you don’t know how to apply common functions to n-dimensional arrays (without using for-loops), or if you want to understand axis and shape properties for n-dimensional arrays, this article might be of help. Learning Objectives After reading, you should be able to: Understand the difference between one-, two- and n-dimensional arrays in NumPy; Understand how to apply some linear algebra operations to n-dimensional arrays without using for-loops; Understand axis and shape properties for n-dimensional arrays. The Basics NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes. For example, the array for the coordinates of a point in 3D space, [1, 2, 1], has one axis. That axis has 3 elements in it, so we say it has a length of 3. In the example pictured below, the array has 2 axes. The first axis has a length of 2, the second axis has a length of 3. [[1., 0., 0.], [0., 1., 2.]] NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less functionality. The more important attributes of an ndarray object are: ndarray.ndim the number of axes (dimensions) of the array. ndarray.shape the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim. ndarray.size the total number of elements of the array. This is equal to the product of the elements of shape. ndarray.dtype an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples. ndarray.itemsize the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize. ndarray.data the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities. An example >>> 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) <class 'numpy.ndarray'> >>> b = np.array([6, 7, 8]) >>> b array([6, 7, 8]) >>> type(b) <class 'numpy.ndarray'> Array Creation 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. >>> 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 frequent error consists in calling array with multiple arguments, rather than providing a single sequence as an argument. >>> a = np.array(1, 2, 3, 4) # WRONG Traceback (most recent call last): ... TypeError: array() takes from 1 to 2 positional arguments but 4 were given >>> a = np.array([1, 2, 3, 4]) # RIGHT array transforms sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on. >>> b = np.array([(1.5, 2, 3), (4, 5, 6)]) >>> b array([[1.5, 2. , 3. ], [4. , 5. , 6. ]]) The type of the array can also be explicitly specified at creation time: >>> c = np.array([[1, 2], [3, 4]], dtype=complex) >>> c array([[1.+0.j, 2.+0.j], [3.+0.j, 4.+0.j]]) 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, but it can be specified via the key word argument dtype. >>> 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) 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)) array([[3.73603959e-262, 6.02658058e-154, 6.55490914e-260], # may vary [5.30498948e-313, 3.14673309e-307, 1.00000000e+000]]) To create sequences of numbers, NumPy provides the arange function which is analogous to the Python built-in range, but returns an array. >>> 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]) 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: >>> 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) See also array, zeros, zeros_like, ones, ones_like, empty, empty_like, arange, linspace, numpy.random.Generator.rand, numpy.random.Generator.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. >>> a = np.arange(6) # 1d array >>> print(a) [0 1 2 3 4 5] >>> >>> b = np.arange(12).reshape(4, 3) # 2d array >>> print(b) [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] >>> >>> c = np.arange(24).reshape(2, 3, 4) # 3d array >>> print(c) [[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]] 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: >>> print(np.arange(10000)) [ 0 1 2 ... 9997 9998 9999] >>> >>> print(np.arange(10000).reshape(100, 100)) [[ 0 1 2 ... 97 98 99] [ 100 101 102 ... 197 198 199] [ 200 201 202 ... 297 298 299] ... [9700 9701 9702 ... 9797 9798 9799] [9800 9801 9802 ... 9897 9898 9899] [9900 9901 9902 ... 9997 9998 9999]] To disable this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions. >>> np.set_printoptions(threshold=sys.maxsize) # sys module should be imported Basic Operations Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result. >>> a = np.array([20, 30, 40, 50]) >>> b = np.arange(4) >>> b array([0, 1, 2, 3]) >>> c = a - b >>> c array([20, 29, 38, 47]) >>> b**2 array([0, 1, 4, 9]) >>> 10 * np.sin(a) array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854]) >>> a < 35 array([ True, True, False, False]) 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: >>> A = np.array([[1, 1], ... [0, 1]]) >>> B = np.array([[2, 0], ... [3, 4]]) >>> A * B # elementwise product array([[2, 0], [0, 4]]) >>> A @ B # matrix product array([[5, 4], [3, 4]]) >>> A.dot(B) # another matrix product array([[5, 4], [3, 4]]) Some operations, such as += and *=, act in place to modify an existing array rather than create a new one. >>> rg = np.random.default_rng(1) # create instance of default random number generator >>> a = np.ones((2, 3), dtype=int) >>> b = rg.random((2, 3)) >>> a *= 3 >>> a array([[3, 3, 3], [3, 3, 3]]) >>> b += a >>> b array([[3.51182162, 3.9504637 , 3.14415961], [3.94864945, 3.31183145, 3.42332645]]) >>> a += b # b is not automatically converted to integer type Traceback (most recent call last): ... numpy.core._exceptions._UFuncOutputCastingError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('int64') with casting rule 'same_kind' 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). >>> a = np.ones(3, dtype=np.int32) >>> b = np.linspace(0, pi, 3) >>> b.dtype.name 'float64' >>> c = a + b >>> c array([1. , 2.57079633, 4.14159265]) >>> c.dtype.name 'float64' >>> d = np.exp(c * 1j) >>> d array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j, -0.54030231-0.84147098j]) >>> d.dtype.name 'complex128' Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. >>> a = rg.random((2, 3)) >>> a array([[0.82770259, 0.40919914, 0.54959369], [0.02755911, 0.75351311, 0.53814331]]) >>> a.sum() 3.1057109529998157 >>> a.min() 0.027559113243068367 >>> a.max() 0.8277025938204418 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: >>> b = np.arange(12).reshape(3, 4) >>> b array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> >>> b.sum(axis=0) # sum of each column array([12, 15, 18, 21]) >>> >>> b.min(axis=1) # min of each row array([0, 4, 8]) >>> >>> b.cumsum(axis=1) # cumulative sum along each row array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]]) 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. >>> B = np.arange(3) >>> B array([0, 1, 2]) >>> np.exp(B) array([1. , 2.71828183, 7.3890561 ]) >>> np.sqrt(B) array([0. , 1. , 1.41421356]) >>> C = np.array([2., -1., 4.]) >>> np.add(B, C) array([2., 0., 6.]) See also all, any, apply_along_axis, argmax, argmin, argsort, average, bincount, ceil, clip, conj, corrcoef, cov, cross, cumprod, cumsum, diff, dot, floor, inner, invert, 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. >>> a = np.arange(10)**3 >>> a array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]) >>> a[2] 8 >>> a[2:5] array([ 8, 27, 64]) >>> # equivalent to a[0:6:2] = 1000; >>> # from start to position 6, exclusive, set every 2nd element to 1000 >>> a[:6:2] = 1000 >>> a array([1000, 1, 1000, 27, 1000, 125, 216, 343, 512, 729]) >>> a[::-1] # reversed a array([ 729, 512, 343, 216, 125, 1000, 27, 1000, 1, 1000]) >>> for i in a: ... print(i**(1 / 3.)) ... 9.999999999999998 1.0 9.999999999999998 3.0 9.999999999999998 4.999999999999999 5.999999999999999 6.999999999999999 7.999999999999999 8.999999999999998 Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas: >>> def f(x, y): ... return 10 * x + y ... >>> b = np.fromfunction(f, (5, 4), dtype=int) >>> b array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]]) >>> b[2, 3] 23 >>> b[0:5, 1] # each row in the second column of b array([ 1, 11, 21, 31, 41]) >>> b[:, 1] # equivalent to the previous example array([ 1, 11, 21, 31, 41]) >>> b[1:3, :] # each column in the second and third row of b array([[10, 11, 12, 13], [20, 21, 22, 23]]) When fewer indices are provided than the number of axes, the missing indices are considered complete slices: >>> b[-1] # the last row. Equivalent to b[-1, :] array([40, 41, 42, 43]) 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, :]. >>> c = np.array([[[ 0, 1, 2], # a 3D array (two stacked 2D arrays) ... [ 10, 12, 13]], ... [[100, 101, 102], ... [110, 112, 113]]]) >>> c.shape (2, 2, 3) >>> c[1, ...] # same as c[1, :, :] or c[1] array([[100, 101, 102], [110, 112, 113]]) >>> c[..., 2] # same as c[:, :, 2] array([[ 2, 13], [102, 113]]) Iterating over multidimensional arrays is done with respect to the first axis: >>> for row in b: ... print(row) ... [0 1 2 3] [10 11 12 13] [20 21 22 23] [30 31 32 33] [40 41 42 43] 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: >>> for element in b.flat: ... print(element) ... 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43 See also Indexing on ndarrays, Indexing routines (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: >>> a = np.floor(10 * rg.random((3, 4))) >>> a array([[3., 7., 3., 4.], [1., 4., 2., 2.], [7., 2., 4., 9.]]) >>> a.shape (3, 4) 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: >>> a.ravel() # returns the array, flattened array([3., 7., 3., 4., 1., 4., 2., 2., 7., 2., 4., 9.]) >>> a.reshape(6, 2) # returns the array with a modified shape array([[3., 7.], [3., 4.], [1., 4.], [2., 2.], [7., 2.], [4., 9.]]) >>> a.T # returns the array, transposed array([[3., 1., 7.], [7., 4., 2.], [3., 2., 4.], [4., 2., 9.]]) >>> a.T.shape (4, 3) >>> a.shape (3, 4) 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: >>> a array([[3., 7., 3., 4.], [1., 4., 2., 2.], [7., 2., 4., 9.]]) >>> a.resize((2, 6)) >>> a array([[3., 7., 3., 4., 1., 4.], [2., 2., 7., 2., 4., 9.]]) If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated: >>> a.reshape(3, -1) array([[3., 7., 3., 4.], [1., 4., 2., 2.], [7., 2., 4., 9.]]) See also ndarray.shape, reshape, resize, ravel Stacking together different arrays Several arrays can be stacked together along different axes: >>> a = np.floor(10 * rg.random((2, 2))) >>> a array([[9., 7.], [5., 2.]]) >>> b = np.floor(10 * rg.random((2, 2))) >>> b array([[1., 9.], [5., 1.]]) >>> np.vstack((a, b)) array([[9., 7.], [5., 2.], [1., 9.], [5., 1.]]) >>> np.hstack((a, b)) array([[9., 7., 1., 9.], [5., 2., 5., 1.]]) The function column_stack stacks 1D arrays as columns into a 2D array. It is equivalent to hstack only for 2D arrays: >>> from numpy import newaxis >>> np.column_stack((a, b)) # with 2D arrays array([[9., 7., 1., 9.], [5., 2., 5., 1.]]) >>> a = np.array([4., 2.]) >>> b = np.array([3., 8.]) >>> np.column_stack((a, b)) # returns a 2D array array([[4., 3.], [2., 8.]]) >>> np.hstack((a, b)) # the result is different array([4., 2., 3., 8.]) >>> a[:, newaxis] # view `a` as a 2D column vector array([[4.], [2.]]) >>> np.column_stack((a[:, newaxis], b[:, newaxis])) array([[4., 3.], [2., 8.]]) >>> np.hstack((a[:, newaxis], b[:, newaxis])) # the result is the same array([[4., 3.], [2., 8.]]) On the other hand, the function row_stack is equivalent to vstack for any input arrays. In fact, row_stack is an alias for vstack: >>> np.column_stack is np.hstack False >>> np.row_stack is np.vstack True In general, for arrays 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 :. >>> np.r_[1:4, 0, 4] array([1, 2, 3, 0, 4]) 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: >>> a = np.floor(10 * rg.random((2, 12))) >>> a array([[6., 7., 6., 9., 0., 5., 4., 0., 6., 8., 5., 2.], [8., 5., 5., 7., 1., 8., 6., 7., 1., 8., 1., 0.]]) >>> # Split `a` into 3 >>> np.hsplit(a, 3) [array([[6., 7., 6., 9.], [8., 5., 5., 7.]]), array([[0., 5., 4., 0.], [1., 8., 6., 7.]]), array([[6., 8., 5., 2.], [1., 8., 1., 0.]])] >>> # Split `a` after the third and the fourth column >>> np.hsplit(a, (3, 4)) [array([[6., 7., 6.], [8., 5., 5.]]), array([[9.], [7.]]), array([[0., 5., 4., 0., 6., 8., 5., 2.], [1., 8., 6., 7., 1., 8., 1., 0.]])] 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 objects or their data. >>> a = np.array([[ 0, 1, 2, 3], ... [ 4, 5, 6, 7], ... [ 8, 9, 10, 11]]) >>> b = a # no new object is created >>> b is a # a and b are two names for the same ndarray object True Python passes mutable objects as references, so function calls make no copy. >>> def f(x): ... print(id(x)) ... >>> id(a) # id is a unique identifier of an object 148293216 # may vary >>> f(a) 148293216 # may vary 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. >>> c = a.view() >>> c is a False >>> c.base is a # c is a view of the data owned by a True >>> c.flags.owndata False >>> >>> c = c.reshape((2, 6)) # a's shape doesn't change >>> a.shape (3, 4) >>> c[0, 4] = 1234 # a's data changes >>> a array([[ 0, 1, 2, 3], [1234, 5, 6, 7], [ 8, 9, 10, 11]]) Slicing an array returns a view of it: >>> s = a[:, 1:3] >>> s[:] = 10 # s[:] is a view of s. Note the difference between s = 10 and s[:] = 10 >>> a array([[ 0, 10, 10, 3], [1234, 10, 10, 7], [ 8, 10, 10, 11]]) Deep Copy The copy method makes a complete copy of the array and its data. >>> d = a.copy() # a new array object with new data is created >>> d is a False >>> d.base is a # d doesn't share anything with a False >>> d[0, 0] = 9999 >>> a array([[ 0, 10, 10, 3], [1234, 10, 10, 7], [ 8, 10, 10, 11]]) Sometimes copy should be called after slicing if the original array is not required anymore. For example, suppose a is a huge intermediate result and the final result b only contains a small fraction of a, a deep copy should be made when constructing b with slicing: >>> a = np.arange(int(1e8)) >>> b = a[:100].copy() >>> del a # the memory of ``a`` can be released. If b = a[:100] is used instead, a is referenced by b and will persist in memory even if del a is executed. 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. Advanced 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 >>> a = np.arange(12)**2 # the first 12 square numbers >>> i = np.array([1, 1, 3, 8, 5]) # an array of indices >>> a[i] # the elements of `a` at the positions `i` array([ 1, 1, 9, 64, 25]) >>> >>> j = np.array([[3, 4], [9, 7]]) # a bidimensional array of indices >>> a[j] # the same shape as `j` array([[ 9, 16], [81, 49]]) 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. >>> palette = np.array([[0, 0, 0], # black ... [255, 0, 0], # red ... [0, 255, 0], # green ... [0, 0, 255], # blue ... [255, 255, 255]]) # white >>> image = np.array([[0, 1, 2, 0], # each value corresponds to a color in the palette ... [0, 3, 4, 0]]) >>> palette[image] # the (2, 4, 3) color image array([[[ 0, 0, 0], [255, 0, 0], [ 0, 255, 0], [ 0, 0, 0]], [[ 0, 0, 0], [ 0, 0, 255], [255, 255, 255], [ 0, 0, 0]]]) We can also give indexes for more than one dimension. The arrays of indices for each dimension must have the same shape. >>> a = np.arange(12).reshape(3, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> i = np.array([[0, 1], # indices for the first dim of `a` ... [1, 2]]) >>> j = np.array([[2, 1], # indices for the second dim ... [3, 3]]) >>> >>> a[i, j] # i and j must have equal shape array([[ 2, 5], [ 7, 11]]) >>> >>> a[i, 2] array([[ 2, 6], [ 6, 10]]) >>> >>> a[:, j] array([[[ 2, 1], [ 3, 3]], [[ 6, 5], [ 7, 7]], [[10, 9], [11, 11]]]) In Python, arr[i, j] is exactly the same as arr[(i, j)]—so we can put i and j in a tuple and then do the indexing with that. >>> l = (i, j) >>> # equivalent to a[i, j] >>> a[l] array([[ 2, 5], [ 7, 11]]) 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. >>> s = np.array([i, j]) >>> # not what we want >>> a[s] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: index 3 is out of bounds for axis 0 with size 3 >>> # same as `a[i, j]` >>> a[tuple(s)] array([[ 2, 5], [ 7, 11]]) Another common use of indexing with arrays is the search of the maximum value of time-dependent series: >>> time = np.linspace(20, 145, 5) # time scale >>> data = np.sin(np.arange(20)).reshape(5, 4) # 4 time-dependent series >>> time array([ 20. , 51.25, 82.5 , 113.75, 145. ]) >>> data array([[ 0. , 0.84147098, 0.90929743, 0.14112001], [-0.7568025 , -0.95892427, -0.2794155 , 0.6569866 ], [ 0.98935825, 0.41211849, -0.54402111, -0.99999021], [-0.53657292, 0.42016704, 0.99060736, 0.65028784], [-0.28790332, -0.96139749, -0.75098725, 0.14987721]]) >>> # index of the maxima for each series >>> ind = data.argmax(axis=0) >>> ind array([2, 0, 3, 1]) >>> # times corresponding to the maxima >>> time_max = time[ind] >>> >>> data_max = data[ind, range(data.shape[1])] # => data[ind[0], 0], data[ind[1], 1]... >>> time_max array([ 82.5 , 20. , 113.75, 51.25]) >>> data_max array([0.98935825, 0.84147098, 0.99060736, 0.6569866 ]) >>> np.all(data_max == data.max(axis=0)) True You can also use indexing with arrays as a target to assign to: >>> a = np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> a[[1, 3, 4]] = 0 >>> a array([0, 0, 2, 0, 0]) However, when the list of indices contains repetitions, the assignment is done several times, leaving behind the last value: >>> a = np.arange(5) >>> a[[0, 0, 2]] = [1, 2, 3] >>> a array([2, 1, 3, 3, 4]) This is reasonable enough, but watch out if you want to use Python’s += construct, as it may not do what you expect: >>> a = np.arange(5) >>> a[[0, 0, 2]] += 1 >>> a array([1, 1, 3, 3, 4]) 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: >>> a = np.arange(12).reshape(3, 4) >>> b = a > 4 >>> b # `b` is a boolean with `a`'s shape array([[False, False, False, False], [False, True, True, True], [ True, True, True, True]]) >>> a[b] # 1d array with the selected elements array([ 5, 6, 7, 8, 9, 10, 11]) This property can be very useful in assignments: >>> a[b] = 0 # All elements of `a` higher than 4 become 0 >>> a array([[0, 1, 2, 3], [4, 0, 0, 0], [0, 0, 0, 0]]) You can look at the following example to see how to use boolean indexing to generate an image of the Mandelbrot set: >>> import numpy as np >>> import matplotlib.pyplot as plt >>> def mandelbrot(h, w, maxit=20, r=2): ... """Returns an image of the Mandelbrot fractal of size (h,w).""" ... x = np.linspace(-2.5, 1.5, 4*h+1) ... y = np.linspace(-1.5, 1.5, 3*w+1) ... A, B = np.meshgrid(x, y) ... C = A + B*1j ... z = np.zeros_like(C) ... divtime = maxit + np.zeros(z.shape, dtype=int) ... ... for i in range(maxit): ... z = z**2 + C ... diverge = abs(z) > r # who is diverging ... div_now = diverge & (divtime == maxit) # who is diverging now ... divtime[div_now] = i # note when ... z[diverge] = r # avoid diverging too much ... ... return divtime >>> plt.imshow(mandelbrot(400, 400)) 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: >>> a = np.arange(12).reshape(3, 4) >>> b1 = np.array([False, True, True]) # first dim selection >>> b2 = np.array([True, False, True, False]) # second dim selection >>> >>> a[b1, :] # selecting rows array([[ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> >>> a[b1] # same thing array([[ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> >>> a[:, b2] # selecting columns array([[ 0, 2], [ 4, 6], [ 8, 10]]) >>> >>> a[b1, b2] # a weird thing to do array([ 4, 10]) 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: >>> a = np.array([2, 3, 4, 5]) >>> b = np.array([8, 5, 4]) >>> c = np.array([5, 4, 6, 8, 3]) >>> ax, bx, cx = np.ix_(a, b, c) >>> ax array([[[2]], [[3]], [[4]], [[5]]]) >>> bx array([[[8], [5], [4]]]) >>> cx array([[[5, 4, 6, 8, 3]]]) >>> ax.shape, bx.shape, cx.shape ((4, 1, 1), (1, 3, 1), (1, 1, 5)) >>> result = ax + bx * cx >>> result array([[[42, 34, 50, 66, 26], [27, 22, 32, 42, 17], [22, 18, 26, 34, 14]], [[43, 35, 51, 67, 27], [28, 23, 33, 43, 18], [23, 19, 27, 35, 15]], [[44, 36, 52, 68, 28], [29, 24, 34, 44, 19], [24, 20, 28, 36, 16]], [[45, 37, 53, 69, 29], [30, 25, 35, 45, 20], [25, 21, 29, 37, 17]]]) >>> result[3, 2, 4] 17 >>> a[3] + b[2] * c[4] 17 You could also implement the reduce as follows: >>> def ufunc_reduce(ufct, *vectors): ... vs = np.ix_(*vectors) ... r = ufct.identity ... for v in vs: ... r = ufct(r, v) ... return r and then use it as: >>> ufunc_reduce(np.add, a, b, c) array([[[15, 14, 16, 18, 13], [12, 11, 13, 15, 10], [11, 10, 12, 14, 9]], [[16, 15, 17, 19, 14], [13, 12, 14, 16, 11], [12, 11, 13, 15, 10]], [[17, 16, 18, 20, 15], [14, 13, 15, 17, 12], [13, 12, 14, 16, 11]], [[18, 17, 19, 21, 16], [15, 14, 16, 18, 13], [14, 13, 15, 17, 12]]]) 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. 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: >>> a = np.arange(30) >>> b = a.reshape((2, -1, 3)) # -1 means "whatever is needed" >>> b.shape (2, 5, 3) >>> b array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]], [[15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]]]) 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: >>> x = np.arange(0, 10, 2) >>> y = np.arange(5) >>> m = np.vstack([x, y]) >>> m array([[0, 2, 4, 6, 8], [0, 1, 2, 3, 4]]) >>> xy = np.hstack([x, y]) >>> xy array([0, 2, 4, 6, 8, 0, 1, 2, 3, 4]) 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 a vector of the bin edges. 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. >>> import numpy as np >>> rg = np.random.default_rng(1) >>> import matplotlib.pyplot as plt >>> # Build a vector of 10000 normal deviates with variance 0.5^2 and mean 2 >>> mu, sigma = 2, 0.5 >>> v = rg.normal(mu, sigma, 10000) >>> # Plot a normalized histogram with 50 bins >>> plt.hist(v, bins=50, density=True) # matplotlib version (plot) >>> # Compute the histogram with numpy and then plot it >>> (n, bins) = np.histogram(v, bins=50, density=True) # NumPy version (no plot) >>> plt.plot(.5 * (bins[1:] + bins[:-1]), n) With Matplotlib >=3.4 you can also use plt.stairs(n, bins). Further reading The Python tutorial Command Reference SciPy Tutorial SciPy Lecture Notes A matlab, R, IDL, NumPy/SciPy dictionary tutorial-svd
numpy.user.quickstart
numpy.ndarray.newbyteorder method ndarray.newbyteorder(new_order='S', /) Return the array with the same data viewed with a different byte order. Equivalent to: arr.view(arr.dtype.newbytorder(new_order)) Changes are also made in all fields and sub-arrays of the array data type. Parameters new_orderstring, optional Byte order to force; a value from the byte order specifications below. new_order codes can be any of: ‘S’ - swap dtype from current to opposite endian {‘<’, ‘little’} - little endian {‘>’, ‘big’} - big endian {‘=’, ‘native’} - native order, equivalent to sys.byteorder {‘|’, ‘I’} - ignore (no change to byte order) The default value (‘S’) results in swapping the current byte order. Returns new_arrarray New array object with the dtype reflecting given change to the byte order.
numpy.reference.generated.numpy.ndarray.newbyteorder
numpy.ndarray.nonzero method ndarray.nonzero() Return the indices of the elements that are non-zero. Refer to numpy.nonzero for full documentation. See also numpy.nonzero equivalent function
numpy.reference.generated.numpy.ndarray.nonzero
numpy.ndarray.partition method ndarray.partition(kth, axis=- 1, kind='introselect', order=None) Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined. New in version 1.8.0. Parameters kthint or sequence of ints Element index to partition by. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once. Deprecated since version 1.22.0: Passing booleans as index is deprecated. axisint, optional Axis along which to sort. Default is -1, which means sort along the last axis. kind{‘introselect’}, optional Selection algorithm. Default is ‘introselect’. orderstr or list of str, optional When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need to be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. See also numpy.partition Return a parititioned copy of an array. argpartition Indirect partition. sort Full sort. Notes See np.partition for notes on the different algorithms. Examples >>> a = np.array([3, 4, 2, 1]) >>> a.partition(3) >>> a array([2, 1, 3, 4]) >>> a.partition((1, 3)) >>> a array([1, 2, 3, 4])
numpy.reference.generated.numpy.ndarray.partition
numpy.ndarray.prod method ndarray.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True) Return the product of the array elements over the given axis Refer to numpy.prod for full documentation. See also numpy.prod equivalent function
numpy.reference.generated.numpy.ndarray.prod
numpy.ndarray.ptp method ndarray.ptp(axis=None, out=None, keepdims=False) Peak to peak (maximum - minimum) value along a given axis. Refer to numpy.ptp for full documentation. See also numpy.ptp equivalent function
numpy.reference.generated.numpy.ndarray.ptp
numpy.ndarray.put method ndarray.put(indices, values, mode='raise') Set a.flat[n] = values[n] for all n in indices. Refer to numpy.put for full documentation. See also numpy.put equivalent function
numpy.reference.generated.numpy.ndarray.put
numpy.ndarray.ravel method ndarray.ravel([order]) Return a flattened array. Refer to numpy.ravel for full documentation. See also numpy.ravel equivalent function ndarray.flat a flat iterator on the array.
numpy.reference.generated.numpy.ndarray.ravel
numpy.ndarray.real attribute ndarray.real The real part of the array. See also numpy.real equivalent function Examples >>> x = np.sqrt([1+0j, 0+1j]) >>> x.real array([ 1. , 0.70710678]) >>> x.real.dtype dtype('float64')
numpy.reference.generated.numpy.ndarray.real
numpy.ndarray.repeat method ndarray.repeat(repeats, axis=None) Repeat elements of an array. Refer to numpy.repeat for full documentation. See also numpy.repeat equivalent function
numpy.reference.generated.numpy.ndarray.repeat
numpy.ndarray.reshape method ndarray.reshape(shape, order='C') Returns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation. See also numpy.reshape equivalent function Notes Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).
numpy.reference.generated.numpy.ndarray.reshape
numpy.ndarray.resize method ndarray.resize(new_shape, refcheck=True) Change shape and size of array in-place. Parameters new_shapetuple of ints, or n ints Shape of resized array. refcheckbool, optional If False, reference count will not be checked. Default is True. Returns None Raises ValueError If a does not own its own data or references or views to it exist, and the data memory must be changed. PyPy only: will always raise if the data memory must be changed, since there is no reliable way to determine if references or views to it exist. SystemError If the order keyword argument is specified. This behaviour is a bug in NumPy. See also resize Return a new array with the specified shape. Notes This reallocates space for the data area if necessary. Only contiguous arrays (data elements consecutive in memory) can be resized. The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False. Examples Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped: >>> a = np.array([[0, 1], [2, 3]], order='C') >>> a.resize((2, 1)) >>> a array([[0], [1]]) >>> a = np.array([[0, 1], [2, 3]], order='F') >>> a.resize((2, 1)) >>> a array([[0], [2]]) Enlarging an array: as above, but missing entries are filled with zeros: >>> b = np.array([[0, 1], [2, 3]]) >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple >>> b array([[0, 1, 2], [3, 0, 0]]) Referencing an array prevents resizing… >>> c = a >>> a.resize((1, 1)) Traceback (most recent call last): ... ValueError: cannot resize an array that references or is referenced ... Unless refcheck is False: >>> a.resize((1, 1), refcheck=False) >>> a array([[0]]) >>> c array([[0]])
numpy.reference.generated.numpy.ndarray.resize
numpy.ndarray.round method ndarray.round(decimals=0, out=None) Return a with each element rounded to the given number of decimals. Refer to numpy.around for full documentation. See also numpy.around equivalent function
numpy.reference.generated.numpy.ndarray.round
numpy.ndarray.searchsorted method ndarray.searchsorted(v, side='left', sorter=None) Find indices where elements of v should be inserted in a to maintain order. For full documentation, see numpy.searchsorted See also numpy.searchsorted equivalent function
numpy.reference.generated.numpy.ndarray.searchsorted
numpy.ndarray.setfield method ndarray.setfield(val, dtype, offset=0) Put a value into a specified place in a field defined by a data-type. Place val into a’s field defined by dtype and beginning offset bytes into the field. Parameters valobject Value to be placed in field. dtypedtype object Data-type of the field in which to place val. offsetint, optional The number of bytes into the field at which to place val. Returns None See also getfield Examples >>> x = np.eye(3) >>> x.getfield(np.float64) array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) >>> x.setfield(3, np.int32) >>> x.getfield(np.int32) array([[3, 3, 3], [3, 3, 3], [3, 3, 3]], dtype=int32) >>> x array([[1.0e+000, 1.5e-323, 1.5e-323], [1.5e-323, 1.0e+000, 1.5e-323], [1.5e-323, 1.5e-323, 1.0e+000]]) >>> x.setfield(np.eye(3), np.int32) >>> x array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
numpy.reference.generated.numpy.ndarray.setfield
numpy.ndarray.setflags method ndarray.setflags(write=None, align=None, uic=None) Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively. These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.) Parameters writebool, optional Describes whether or not a can be written to. alignbool, optional Describes whether or not a is aligned properly for its type. uicbool, optional Describes whether or not a is a copy of another “base” array. Notes Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only four of which can be changed by the user: WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED. WRITEABLE (W) the data area can be written to; ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler); UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY; WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array. All flags can be accessed using the single (upper case) letter as well as the full name. Examples >>> y = np.array([[3, 1, 7], ... [2, 0, 0], ... [8, 5, 9]]) >>> y array([[3, 1, 7], [2, 0, 0], [8, 5, 9]]) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False >>> y.setflags(write=0, align=0) >>> y.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : False WRITEBACKIFCOPY : False UPDATEIFCOPY : False >>> y.setflags(uic=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot set WRITEBACKIFCOPY flag to True
numpy.reference.generated.numpy.ndarray.setflags
numpy.ndarray.shape attribute ndarray.shape Tuple of array dimensions. The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required. See also numpy.reshape similar function ndarray.reshape similar method Examples >>> x = np.array([1, 2, 3, 4]) >>> x.shape (4,) >>> y = np.zeros((2, 3, 4)) >>> y.shape (2, 3, 4) >>> y.shape = (3, 8) >>> y array([[ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0.]]) >>> y.shape = (3, 6) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: total size of new array must be unchanged >>> np.zeros((4,2))[::2].shape = (-1,) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Incompatible shape for in-place modification. Use `.reshape()` to make a copy with the desired shape.
numpy.reference.generated.numpy.ndarray.shape
numpy.ndarray.size attribute ndarray.size Number of elements in the array. Equal to np.prod(a.shape), i.e., the product of the array’s dimensions. Notes a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type. Examples >>> x = np.zeros((3, 5, 2), dtype=np.complex128) >>> x.size 30 >>> np.prod(x.shape) 30
numpy.reference.generated.numpy.ndarray.size
numpy.ndarray.sort method ndarray.sort(axis=- 1, kind=None, order=None) Sort an array in-place. Refer to numpy.sort for full documentation. Parameters axisint, optional Axis along which to sort. Default is -1, which means sort along the last axis. kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. The ‘mergesort’ option is retained for backwards compatibility. Changed in version 1.15.0: The ‘stable’ option was added. orderstr or list of str, optional When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. See also numpy.sort Return a sorted copy of an array. numpy.argsort Indirect sort. numpy.lexsort Indirect stable sort on multiple keys. numpy.searchsorted Find elements in sorted array. numpy.partition Partial sort. Notes See numpy.sort for notes on the different sorting algorithms. Examples >>> a = np.array([[1,4], [3,1]]) >>> a.sort(axis=1) >>> a array([[1, 4], [1, 3]]) >>> a.sort(axis=0) >>> a array([[1, 3], [1, 4]]) Use the order keyword to specify a field to use when sorting a structured array: >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)]) >>> a.sort(order='y') >>> a array([(b'c', 1), (b'a', 2)], dtype=[('x', 'S1'), ('y', '<i8')])
numpy.reference.generated.numpy.ndarray.sort
numpy.ndarray.squeeze method ndarray.squeeze(axis=None) Remove axes of length one from a. Refer to numpy.squeeze for full documentation. See also numpy.squeeze equivalent function
numpy.reference.generated.numpy.ndarray.squeeze
numpy.ndarray.std method ndarray.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True) Returns the standard deviation of the array elements along given axis. Refer to numpy.std for full documentation. See also numpy.std equivalent function
numpy.reference.generated.numpy.ndarray.std
numpy.ndarray.strides attribute ndarray.strides Tuple of bytes to step in each dimension when traversing an array. The byte offset of element (i[0], i[1], ..., i[n]) in an array a is: offset = sum(np.array(i) * a.strides) A more detailed explanation of strides can be found in the “ndarray.rst” file in the NumPy reference guide. See also numpy.lib.stride_tricks.as_strided Notes Imagine an array of 32-bit integers (each 4 bytes): x = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=np.int32) This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be (20, 4). Examples >>> y = np.reshape(np.arange(2*3*4), (2,3,4)) >>> y array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]) >>> y.strides (48, 16, 4) >>> y[1,1,1] 17 >>> offset=sum(y.strides * np.array((1,1,1))) >>> offset/y.itemsize 17 >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0) >>> x.strides (32, 4, 224, 1344) >>> i = np.array([3,5,2,2]) >>> offset = sum(i * x.strides) >>> x[3,5,2,2] 813 >>> offset / x.itemsize 813
numpy.reference.generated.numpy.ndarray.strides
numpy.ndarray.sum method ndarray.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True) Return the sum of the array elements over the given axis. Refer to numpy.sum for full documentation. See also numpy.sum equivalent function
numpy.reference.generated.numpy.ndarray.sum
numpy.ndarray.swapaxes method ndarray.swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged. Refer to numpy.swapaxes for full documentation. See also numpy.swapaxes equivalent function
numpy.reference.generated.numpy.ndarray.swapaxes
numpy.ndarray.T attribute ndarray.T The transposed array. Same as self.transpose(). See also transpose Examples >>> x = np.array([[1.,2.],[3.,4.]]) >>> x array([[ 1., 2.], [ 3., 4.]]) >>> x.T array([[ 1., 3.], [ 2., 4.]]) >>> x = np.array([1.,2.,3.,4.]) >>> x array([ 1., 2., 3., 4.]) >>> x.T array([ 1., 2., 3., 4.])
numpy.reference.generated.numpy.ndarray.t
numpy.ndarray.take method ndarray.take(indices, axis=None, out=None, mode='raise') Return an array formed from the elements of a at the given indices. Refer to numpy.take for full documentation. See also numpy.take equivalent function
numpy.reference.generated.numpy.ndarray.take
numpy.ndarray.tobytes method ndarray.tobytes(order='C') Construct Python bytes containing the raw data bytes in the array. Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter. New in version 1.9.0. Parameters order{‘C’, ‘F’, ‘A’}, optional Controls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’. Returns sbytes Python bytes exhibiting a copy of a’s raw data. Examples >>> x = np.array([[0, 1], [2, 3]], dtype='<u2') >>> x.tobytes() b'\x00\x00\x01\x00\x02\x00\x03\x00' >>> x.tobytes('C') == x.tobytes() True >>> x.tobytes('F') b'\x00\x00\x02\x00\x01\x00\x03\x00'
numpy.reference.generated.numpy.ndarray.tobytes
numpy.ndarray.tofile method ndarray.tofile(fid, sep='', format='%s') Write array to a file as text or binary (default). Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile(). Parameters fidfile or str or Path An open file object, or a string containing a filename. Changed in version 1.17.0: pathlib.Path objects are now accepted. sepstr Separator between array items for text output. If “” (empty), a binary file is written, equivalent to file.write(a.tobytes()). formatstr Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using “format” % item. Notes This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size. When fid is a file object, array contents are directly written to the file, bypassing the file object’s write method. As a result, tofile cannot be used with files objects supporting compression (e.g., GzipFile) or file-like objects that do not support fileno() (e.g., BytesIO).
numpy.reference.generated.numpy.ndarray.tofile
numpy.ndarray.tolist method ndarray.tolist() Return the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function. If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar. Parameters none Returns yobject, or list of object, or list of list of object, or … The possibly nested list of array elements. Notes The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision. Examples For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2]) >>> a_list = list(a) >>> a_list [1, 2] >>> type(a_list[0]) <class 'numpy.uint32'> >>> a_tolist = a.tolist() >>> a_tolist [1, 2] >>> type(a_tolist[0]) <class 'int'> Additionally, for a 2D array, tolist applies recursively: >>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]] The base case for this recursion is a 0D array: >>> a = np.array(1) >>> list(a) Traceback (most recent call last): ... TypeError: iteration over a 0-d array >>> a.tolist() 1
numpy.reference.generated.numpy.ndarray.tolist
numpy.ndarray.tostring method ndarray.tostring(order='C') A compatibility alias for tobytes, with exactly the same behavior. Despite its name, it returns bytes not strs. Deprecated since version 1.19.0.
numpy.reference.generated.numpy.ndarray.tostring
numpy.ndarray.trace method ndarray.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) Return the sum along diagonals of the array. Refer to numpy.trace for full documentation. See also numpy.trace equivalent function
numpy.reference.generated.numpy.ndarray.trace
numpy.ndarray.transpose method ndarray.transpose(*axes) Returns a view of the array with axes transposed. For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]). Parameters axesNone, tuple of ints, or n ints None or no argument: reverses the order of the axes. tuple of ints: i in the j-th place in the tuple means a’s i-th axis becomes a.transpose()’s j-th axis. n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form) Returns outndarray View of a, with axes suitably permuted. See also transpose Equivalent function ndarray.T Array property returning the array transposed. ndarray.reshape Give a new shape to an array without changing its data. Examples >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.transpose() array([[1, 3], [2, 4]]) >>> a.transpose((1, 0)) array([[1, 3], [2, 4]]) >>> a.transpose(1, 0) array([[1, 3], [2, 4]])
numpy.reference.generated.numpy.ndarray.transpose
numpy.ndarray.var method ndarray.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True) Returns the variance of the array elements, along given axis. Refer to numpy.var for full documentation. See also numpy.var equivalent function
numpy.reference.generated.numpy.ndarray.var
numpy.ndarray.view method ndarray.view([dtype][, type]) New view of array with the same data. Note Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_'). Parameters dtypedata-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter). typePython type, optional Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation. Notes a.view() is used two different ways: a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory. a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. Examples >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) Viewing array data using a different type and dtype: >>> y = x.view(dtype=np.int16, type=np.matrix) >>> y matrix([[513]], dtype=int16) >>> print(type(y)) <class 'numpy.matrix'> Creating a view on a structured array so it can be used in calculations >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) >>> xv = x.view(dtype=np.int8).reshape(-1,2) >>> xv array([[1, 2], [3, 4]], dtype=int8) >>> xv.mean(0) array([2., 3.]) Making changes to the view changes the underlying array >>> xv[0,1] = 20 >>> x array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')]) Using a view to convert an array to a recarray: >>> z = x.view(np.recarray) >>> z.a array([1, 3], dtype=int8) Views share data: >>> x[0] = (9, 10) >>> z[0] (9, 10) Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.: >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16) >>> y = x[:, 0:2] >>> y array([[1, 2], [4, 5]], dtype=int16) >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) Traceback (most recent call last): ... ValueError: To change to a dtype of a different size, the array must be C-contiguous >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 2)], [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')])
numpy.reference.generated.numpy.ndarray.view
numpy.ndindex.ndincr method ndindex.ndincr()[source] Increment the multi-dimensional index by one. This method is for backward compatibility only: do not use. Deprecated since version 1.20.0: This method has been advised against since numpy 1.8.0, but only started emitting DeprecationWarning as of this version.
numpy.reference.generated.numpy.ndindex.ndincr
numpy.nditer.close method nditer.close() Resolve all writeback semantics in writeable operands. New in version 1.15.0. See also Modifying Array Values
numpy.reference.generated.numpy.nditer.close
numpy.nditer.copy method nditer.copy() Get a copy of the iterator in its current state. Examples >>> x = np.arange(10) >>> y = x + 1 >>> it = np.nditer([x, y]) >>> next(it) (array(0), array(1)) >>> it2 = it.copy() >>> next(it2) (array(1), array(2))
numpy.reference.generated.numpy.nditer.copy
numpy.nditer.debug_print method nditer.debug_print() Print the current state of the nditer instance and debug info to stdout.
numpy.reference.generated.numpy.nditer.debug_print
numpy.nditer.enable_external_loop method nditer.enable_external_loop() When the “external_loop” was not used during construction, but is desired, this modifies the iterator to behave as if the flag was specified.
numpy.reference.generated.numpy.nditer.enable_external_loop
numpy.nditer.index attribute nditer.index
numpy.reference.generated.numpy.nditer.index
numpy.nditer.iternext method nditer.iternext() Check whether iterations are left, and perform a single internal iteration without returning the result. Used in the C-style pattern do-while pattern. For an example, see nditer. Returns iternextbool Whether or not there are iterations left.
numpy.reference.generated.numpy.nditer.iternext
numpy.nditer.itersize attribute nditer.itersize
numpy.reference.generated.numpy.nditer.itersize
numpy.nditer.multi_index attribute nditer.multi_index
numpy.reference.generated.numpy.nditer.multi_index
numpy.nditer.operands attribute nditer.operands operands[Slice] The array(s) to be iterated over. Valid only before the iterator is closed.
numpy.reference.generated.numpy.nditer.operands
numpy.nditer.remove_axis method nditer.remove_axis(i, /) Removes axis i from the iterator. Requires that the flag “multi_index” be enabled.
numpy.reference.generated.numpy.nditer.remove_axis
numpy.nditer.remove_multi_index method nditer.remove_multi_index() When the “multi_index” flag was specified, this removes it, allowing the internal iteration structure to be optimized further.
numpy.reference.generated.numpy.nditer.remove_multi_index
numpy.nditer.reset method nditer.reset() Reset the iterator to its initial state.
numpy.reference.generated.numpy.nditer.reset
numpy.nditer.value attribute nditer.value
numpy.reference.generated.numpy.nditer.value
Using Python as glue Many people like to say that Python is a fantastic glue language. Hopefully, this Chapter will convince you that this is true. The first adopters of Python for science were typically people who used it to glue together large application codes running on super-computers. Not only was it much nicer to code in Python than in a shell script or Perl, in addition, the ability to easily extend Python made it relatively easy to create new classes and types specifically adapted to the problems being solved. From the interactions of these early contributors, Numeric emerged as an array-like object that could be used to pass data between these applications. As Numeric has matured and developed into NumPy, people have been able to write more code directly in NumPy. Often this code is fast-enough for production use, but there are still times that there is a need to access compiled code. Either to get that last bit of efficiency out of the algorithm or to make it easier to access widely-available codes written in C/C++ or Fortran. This chapter will review many of the tools that are available for the purpose of accessing code written in other compiled languages. There are many resources available for learning to call other compiled libraries from Python and the purpose of this Chapter is not to make you an expert. The main goal is to make you aware of some of the possibilities so that you will know what to “Google” in order to learn more. Calling other compiled libraries from Python While Python is a great language and a pleasure to code in, its dynamic nature results in overhead that can cause some code ( i.e. raw computations inside of for loops) to be up 10-100 times slower than equivalent code written in a static compiled language. In addition, it can cause memory usage to be larger than necessary as temporary arrays are created and destroyed during computation. For many types of computing needs, the extra slow-down and memory consumption can often not be spared (at least for time- or memory- critical portions of your code). Therefore one of the most common needs is to call out from Python code to a fast, machine-code routine (e.g. compiled using C/C++ or Fortran). The fact that this is relatively easy to do is a big reason why Python is such an excellent high-level language for scientific and engineering programming. Their are two basic approaches to calling compiled code: writing an extension module that is then imported to Python using the import command, or calling a shared-library subroutine directly from Python using the ctypes module. Writing an extension module is the most common method. Warning Calling C-code from Python can result in Python crashes if you are not careful. None of the approaches in this chapter are immune. You have to know something about the way data is handled by both NumPy and by the third-party library being used. Hand-generated wrappers Extension modules were discussed in Writing an extension module. The most basic way to interface with compiled code is to write an extension module and construct a module method that calls the compiled code. For improved readability, your method should take advantage of the PyArg_ParseTuple call to convert between Python objects and C data-types. For standard C data-types there is probably already a built-in converter. For others you may need to write your own converter and use the "O&" format string which allows you to specify a function that will be used to perform the conversion from the Python object to whatever C-structures are needed. Once the conversions to the appropriate C-structures and C data-types have been performed, the next step in the wrapper is to call the underlying function. This is straightforward if the underlying function is in C or C++. However, in order to call Fortran code you must be familiar with how Fortran subroutines are called from C/C++ using your compiler and platform. This can vary somewhat platforms and compilers (which is another reason f2py makes life much simpler for interfacing Fortran code) but generally involves underscore mangling of the name and the fact that all variables are passed by reference (i.e. all arguments are pointers). The advantage of the hand-generated wrapper is that you have complete control over how the C-library gets used and called which can lead to a lean and tight interface with minimal over-head. The disadvantage is that you have to write, debug, and maintain C-code, although most of it can be adapted using the time-honored technique of “cutting-pasting-and-modifying” from other extension modules. Because, the procedure of calling out to additional C-code is fairly regimented, code-generation procedures have been developed to make this process easier. One of these code-generation techniques is distributed with NumPy and allows easy integration with Fortran and (simple) C code. This package, f2py, will be covered briefly in the next section. f2py F2py allows you to automatically construct an extension module that interfaces to routines in Fortran 77/90/95 code. It has the ability to parse Fortran 77/90/95 code and automatically generate Python signatures for the subroutines it encounters, or you can guide how the subroutine interfaces with Python by constructing an interface-definition-file (or modifying the f2py-produced one). Creating source for a basic extension module Probably the easiest way to introduce f2py is to offer a simple example. Here is one of the subroutines contained in a file named add.f C SUBROUTINE ZADD(A,B,C,N) C DOUBLE COMPLEX A(*) DOUBLE COMPLEX B(*) DOUBLE COMPLEX C(*) INTEGER N DO 20 J = 1, N C(J) = A(J)+B(J) 20 CONTINUE END This routine simply adds the elements in two contiguous arrays and places the result in a third. The memory for all three arrays must be provided by the calling routine. A very basic interface to this routine can be automatically generated by f2py: f2py -m add add.f You should be able to run this command assuming your search-path is set-up properly. This command will produce an extension module named addmodule.c in the current directory. This extension module can now be compiled and used from Python just like any other extension module. Creating a compiled extension module You can also get f2py to both compile add.f along with the produced extension module leaving only a shared-library extension file that can be imported from Python: f2py -c -m add add.f This command leaves a file named add.{ext} in the current directory (where {ext} is the appropriate extension for a Python extension module on your platform — so, pyd, etc. ). This module may then be imported from Python. It will contain a method for each subroutine in add (zadd, cadd, dadd, sadd). The docstring of each method contains information about how the module method may be called: >>> import add >>> print(add.zadd.__doc__) zadd(a,b,c,n) Wrapper for ``zadd``. Parameters ---------- a : input rank-1 array('D') with bounds (*) b : input rank-1 array('D') with bounds (*) c : input rank-1 array('D') with bounds (*) n : input int Improving the basic interface The default interface is a very literal translation of the Fortran code into Python. The Fortran array arguments must now be NumPy arrays and the integer argument should be an integer. The interface will attempt to convert all arguments to their required types (and shapes) and issue an error if unsuccessful. However, because it knows nothing about the semantics of the arguments (such that C is an output and n should really match the array sizes), it is possible to abuse this function in ways that can cause Python to crash. For example: >>> add.zadd([1, 2, 3], [1, 2], [3, 4], 1000) will cause a program crash on most systems. Under the covers, the lists are being converted to proper arrays but then the underlying add loop is told to cycle way beyond the borders of the allocated memory. In order to improve the interface, directives should be provided. This is accomplished by constructing an interface definition file. It is usually best to start from the interface file that f2py can produce (where it gets its default behavior from). To get f2py to generate the interface file use the -h option: f2py -h add.pyf -m add add.f This command leaves the file add.pyf in the current directory. The section of this file corresponding to zadd is: subroutine zadd(a,b,c,n) ! in :add:add.f double complex dimension(*) :: a double complex dimension(*) :: b double complex dimension(*) :: c integer :: n end subroutine zadd By placing intent directives and checking code, the interface can be cleaned up quite a bit until the Python module method is both easier to use and more robust. subroutine zadd(a,b,c,n) ! in :add:add.f double complex dimension(n) :: a double complex dimension(n) :: b double complex intent(out),dimension(n) :: c integer intent(hide),depend(a) :: n=len(a) end subroutine zadd The intent directive, intent(out) is used to tell f2py that c is an output variable and should be created by the interface before being passed to the underlying code. The intent(hide) directive tells f2py to not allow the user to specify the variable, n, but instead to get it from the size of a. The depend( a ) directive is necessary to tell f2py that the value of n depends on the input a (so that it won’t try to create the variable n until the variable a is created). After modifying add.pyf, the new Python module file can be generated by compiling both add.f and add.pyf: f2py -c add.pyf add.f The new interface has docstring: >>> import add >>> print(add.zadd.__doc__) c = zadd(a,b) Wrapper for ``zadd``. Parameters ---------- a : input rank-1 array('D') with bounds (n) b : input rank-1 array('D') with bounds (n) Returns ------- c : rank-1 array('D') with bounds (n) Now, the function can be called in a much more robust way: >>> add.zadd([1, 2, 3], [4, 5, 6]) array([5.+0.j, 7.+0.j, 9.+0.j]) Notice the automatic conversion to the correct format that occurred. Inserting directives in Fortran source The nice interface can also be generated automatically by placing the variable directives as special comments in the original Fortran code. Thus, if the source code is modified to contain: C SUBROUTINE ZADD(A,B,C,N) C CF2PY INTENT(OUT) :: C CF2PY INTENT(HIDE) :: N CF2PY DOUBLE COMPLEX :: A(N) CF2PY DOUBLE COMPLEX :: B(N) CF2PY DOUBLE COMPLEX :: C(N) DOUBLE COMPLEX A(*) DOUBLE COMPLEX B(*) DOUBLE COMPLEX C(*) INTEGER N DO 20 J = 1, N C(J) = A(J) + B(J) 20 CONTINUE END Then, one can compile the extension module using: f2py -c -m add add.f The resulting signature for the function add.zadd is exactly the same one that was created previously. If the original source code had contained A(N) instead of A(*) and so forth with B and C, then nearly the same interface can be obtained by placing the INTENT(OUT) :: C comment line in the source code. The only difference is that N would be an optional input that would default to the length of A. A filtering example For comparison with the other methods to be discussed. Here is another example of a function that filters a two-dimensional array of double precision floating-point numbers using a fixed averaging filter. The advantage of using Fortran to index into multi-dimensional arrays should be clear from this example. SUBROUTINE DFILTER2D(A,B,M,N) C DOUBLE PRECISION A(M,N) DOUBLE PRECISION B(M,N) INTEGER N, M CF2PY INTENT(OUT) :: B CF2PY INTENT(HIDE) :: N CF2PY INTENT(HIDE) :: M DO 20 I = 2,M-1 DO 40 J=2,N-1 B(I,J) = A(I,J) + $ (A(I-1,J)+A(I+1,J) + $ A(I,J-1)+A(I,J+1) )*0.5D0 + $ (A(I-1,J-1) + A(I-1,J+1) + $ A(I+1,J-1) + A(I+1,J+1))*0.25D0 40 CONTINUE 20 CONTINUE END This code can be compiled and linked into an extension module named filter using: f2py -c -m filter filter.f This will produce an extension module named filter.so in the current directory with a method named dfilter2d that returns a filtered version of the input. Calling f2py from Python The f2py program is written in Python and can be run from inside your code to compile Fortran code at runtime, as follows: from numpy import f2py with open("add.f") as sourcefile: sourcecode = sourcefile.read() f2py.compile(sourcecode, modulename='add') import add The source string can be any valid Fortran code. If you want to save the extension-module source code then a suitable file-name can be provided by the source_fn keyword to the compile function. Automatic extension module generation If you want to distribute your f2py extension module, then you only need to include the .pyf file and the Fortran code. The distutils extensions in NumPy allow you to define an extension module entirely in terms of this interface file. A valid setup.py file allowing distribution of the add.f module (as part of the package f2py_examples so that it would be loaded as f2py_examples.add) is: def configuration(parent_package='', top_path=None) from numpy.distutils.misc_util import Configuration config = Configuration('f2py_examples',parent_package, top_path) config.add_extension('add', sources=['add.pyf','add.f']) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) Installation of the new package is easy using: pip install . assuming you have the proper permissions to write to the main site- packages directory for the version of Python you are using. For the resulting package to work, you need to create a file named __init__.py (in the same directory as add.pyf). Notice the extension module is defined entirely in terms of the add.pyf and add.f files. The conversion of the .pyf file to a .c file is handled by numpy.disutils. Conclusion The interface definition file (.pyf) is how you can fine-tune the interface between Python and Fortran. There is decent documentation for f2py at F2PY user guide and reference manual. There is also more information on using f2py (including how to use it to wrap C codes) at the “Interfacing With Other Languages” heading of the SciPy Cookbook. The f2py method of linking compiled code is currently the most sophisticated and integrated approach. It allows clean separation of Python with compiled code while still allowing for separate distribution of the extension module. The only draw-back is that it requires the existence of a Fortran compiler in order for a user to install the code. However, with the existence of the free-compilers g77, gfortran, and g95, as well as high-quality commercial compilers, this restriction is not particularly onerous. In our opinion, Fortran is still the easiest way to write fast and clear code for scientific computing. It handles complex numbers, and multi-dimensional indexing in the most straightforward way. Be aware, however, that some Fortran compilers will not be able to optimize code as well as good hand- written C-code. Cython Cython is a compiler for a Python dialect that adds (optional) static typing for speed, and allows mixing C or C++ code into your modules. It produces C or C++ extensions that can be compiled and imported in Python code. If you are writing an extension module that will include quite a bit of your own algorithmic code as well, then Cython is a good match. Among its features is the ability to easily and quickly work with multidimensional arrays. Notice that Cython is an extension-module generator only. Unlike f2py, it includes no automatic facility for compiling and linking the extension module (which must be done in the usual fashion). It does provide a modified distutils class called build_ext which lets you build an extension module from a .pyx source. Thus, you could write in a setup.py file: from Cython.Distutils import build_ext from distutils.extension import Extension from distutils.core import setup import numpy setup(name='mine', description='Nothing', ext_modules=[Extension('filter', ['filter.pyx'], include_dirs=[numpy.get_include()])], cmdclass = {'build_ext':build_ext}) Adding the NumPy include directory is, of course, only necessary if you are using NumPy arrays in the extension module (which is what we assume you are using Cython for). The distutils extensions in NumPy also include support for automatically producing the extension-module and linking it from a .pyx file. It works so that if the user does not have Cython installed, then it looks for a file with the same file-name but a .c extension which it then uses instead of trying to produce the .c file again. If you just use Cython to compile a standard Python module, then you will get a C extension module that typically runs a bit faster than the equivalent Python module. Further speed increases can be gained by using the cdef keyword to statically define C variables. Let’s look at two examples we’ve seen before to see how they might be implemented using Cython. These examples were compiled into extension modules using Cython 0.21.1. Complex addition in Cython Here is part of a Cython module named add.pyx which implements the complex addition functions we previously implemented using f2py: cimport cython cimport numpy as np import numpy as np # We need to initialize NumPy. np.import_array() #@cython.boundscheck(False) def zadd(in1, in2): cdef double complex[:] a = in1.ravel() cdef double complex[:] b = in2.ravel() out = np.empty(a.shape[0], np.complex64) cdef double complex[:] c = out.ravel() for i in range(c.shape[0]): c[i].real = a[i].real + b[i].real c[i].imag = a[i].imag + b[i].imag return out This module shows use of the cimport statement to load the definitions from the numpy.pxd header that ships with Cython. It looks like NumPy is imported twice; cimport only makes the NumPy C-API available, while the regular import causes a Python-style import at runtime and makes it possible to call into the familiar NumPy Python API. The example also demonstrates Cython’s “typed memoryviews”, which are like NumPy arrays at the C level, in the sense that they are shaped and strided arrays that know their own extent (unlike a C array addressed through a bare pointer). The syntax double complex[:] denotes a one-dimensional array (vector) of doubles, with arbitrary strides. A contiguous array of ints would be int[::1], while a matrix of floats would be float[:, :]. Shown commented is the cython.boundscheck decorator, which turns bounds-checking for memory view accesses on or off on a per-function basis. We can use this to further speed up our code, at the expense of safety (or a manual check prior to entering the loop). Other than the view syntax, the function is immediately readable to a Python programmer. Static typing of the variable i is implicit. Instead of the view syntax, we could also have used Cython’s special NumPy array syntax, but the view syntax is preferred. Image filter in Cython The two-dimensional example we created using Fortran is just as easy to write in Cython: cimport numpy as np import numpy as np np.import_array() def filter(img): cdef double[:, :] a = np.asarray(img, dtype=np.double) out = np.zeros(img.shape, dtype=np.double) cdef double[:, ::1] b = out cdef np.npy_intp i, j for i in range(1, a.shape[0] - 1): for j in range(1, a.shape[1] - 1): b[i, j] = (a[i, j] + .5 * ( a[i-1, j] + a[i+1, j] + a[i, j-1] + a[i, j+1]) + .25 * ( a[i-1, j-1] + a[i-1, j+1] + a[i+1, j-1] + a[i+1, j+1])) return out This 2-d averaging filter runs quickly because the loop is in C and the pointer computations are done only as needed. If the code above is compiled as a module image, then a 2-d image, img, can be filtered using this code very quickly using: import image out = image.filter(img) Regarding the code, two things are of note: firstly, it is impossible to return a memory view to Python. Instead, a NumPy array out is first created, and then a view b onto this array is used for the computation. Secondly, the view b is typed double[:, ::1]. This means 2-d array with contiguous rows, i.e., C matrix order. Specifying the order explicitly can speed up some algorithms since they can skip stride computations. Conclusion Cython is the extension mechanism of choice for several scientific Python libraries, including Scipy, Pandas, SAGE, scikit-image and scikit-learn, as well as the XML processing library LXML. The language and compiler are well-maintained. There are several disadvantages of using Cython: When coding custom algorithms, and sometimes when wrapping existing C libraries, some familiarity with C is required. In particular, when using C memory management (malloc and friends), it’s easy to introduce memory leaks. However, just compiling a Python module renamed to .pyx can already speed it up, and adding a few type declarations can give dramatic speedups in some code. It is easy to lose a clean separation between Python and C which makes re-using your C-code for other non-Python-related projects more difficult. The C-code generated by Cython is hard to read and modify (and typically compiles with annoying but harmless warnings). One big advantage of Cython-generated extension modules is that they are easy to distribute. In summary, Cython is a very capable tool for either gluing C code or generating an extension module quickly and should not be over-looked. It is especially useful for people that can’t or won’t write C or Fortran code. ctypes Ctypes is a Python extension module, included in the stdlib, that allows you to call an arbitrary function in a shared library directly from Python. This approach allows you to interface with C-code directly from Python. This opens up an enormous number of libraries for use from Python. The drawback, however, is that coding mistakes can lead to ugly program crashes very easily (just as can happen in C) because there is little type or bounds checking done on the parameters. This is especially true when array data is passed in as a pointer to a raw memory location. The responsibility is then on you that the subroutine will not access memory outside the actual array area. But, if you don’t mind living a little dangerously ctypes can be an effective tool for quickly taking advantage of a large shared library (or writing extended functionality in your own shared library). Because the ctypes approach exposes a raw interface to the compiled code it is not always tolerant of user mistakes. Robust use of the ctypes module typically involves an additional layer of Python code in order to check the data types and array bounds of objects passed to the underlying subroutine. This additional layer of checking (not to mention the conversion from ctypes objects to C-data-types that ctypes itself performs), will make the interface slower than a hand-written extension-module interface. However, this overhead should be negligible if the C-routine being called is doing any significant amount of work. If you are a great Python programmer with weak C skills, ctypes is an easy way to write a useful interface to a (shared) library of compiled code. To use ctypes you must Have a shared library. Load the shared library. Convert the Python objects to ctypes-understood arguments. Call the function from the library with the ctypes arguments. Having a shared library There are several requirements for a shared library that can be used with ctypes that are platform specific. This guide assumes you have some familiarity with making a shared library on your system (or simply have a shared library available to you). Items to remember are: A shared library must be compiled in a special way ( e.g. using the -shared flag with gcc). On some platforms (e.g. Windows), a shared library requires a .def file that specifies the functions to be exported. For example a mylib.def file might contain: LIBRARY mylib.dll EXPORTS cool_function1 cool_function2 Alternatively, you may be able to use the storage-class specifier __declspec(dllexport) in the C-definition of the function to avoid the need for this .def file. There is no standard way in Python distutils to create a standard shared library (an extension module is a “special” shared library Python understands) in a cross-platform manner. Thus, a big disadvantage of ctypes at the time of writing this book is that it is difficult to distribute in a cross-platform manner a Python extension that uses ctypes and includes your own code which should be compiled as a shared library on the users system. Loading the shared library A simple, but robust way to load the shared library is to get the absolute path name and load it using the cdll object of ctypes: lib = ctypes.cdll[<full_path_name>] However, on Windows accessing an attribute of the cdll method will load the first DLL by that name found in the current directory or on the PATH. Loading the absolute path name requires a little finesse for cross-platform work since the extension of shared libraries varies. There is a ctypes.util.find_library utility available that can simplify the process of finding the library to load but it is not foolproof. Complicating matters, different platforms have different default extensions used by shared libraries (e.g. .dll – Windows, .so – Linux, .dylib – Mac OS X). This must also be taken into account if you are using ctypes to wrap code that needs to work on several platforms. NumPy provides a convenience function called ctypeslib.load_library (name, path). This function takes the name of the shared library (including any prefix like ‘lib’ but excluding the extension) and a path where the shared library can be located. It returns a ctypes library object or raises an OSError if the library cannot be found or raises an ImportError if the ctypes module is not available. (Windows users: the ctypes library object loaded using load_library is always loaded assuming cdecl calling convention. See the ctypes documentation under ctypes.windll and/or ctypes.oledll for ways to load libraries under other calling conventions). The functions in the shared library are available as attributes of the ctypes library object (returned from ctypeslib.load_library) or as items using lib['func_name'] syntax. The latter method for retrieving a function name is particularly useful if the function name contains characters that are not allowable in Python variable names. Converting arguments Python ints/longs, strings, and unicode objects are automatically converted as needed to equivalent ctypes arguments The None object is also converted automatically to a NULL pointer. All other Python objects must be converted to ctypes-specific types. There are two ways around this restriction that allow ctypes to integrate with other objects. Don’t set the argtypes attribute of the function object and define an _as_parameter_ method for the object you want to pass in. The _as_parameter_ method must return a Python int which will be passed directly to the function. Set the argtypes attribute to a list whose entries contain objects with a classmethod named from_param that knows how to convert your object to an object that ctypes can understand (an int/long, string, unicode, or object with the _as_parameter_ attribute). NumPy uses both methods with a preference for the second method because it can be safer. The ctypes attribute of the ndarray returns an object that has an _as_parameter_ attribute which returns an integer representing the address of the ndarray to which it is associated. As a result, one can pass this ctypes attribute object directly to a function expecting a pointer to the data in your ndarray. The caller must be sure that the ndarray object is of the correct type, shape, and has the correct flags set or risk nasty crashes if the data-pointer to inappropriate arrays are passed in. To implement the second method, NumPy provides the class-factory function ndpointer in the numpy.ctypeslib module. This class-factory function produces an appropriate class that can be placed in an argtypes attribute entry of a ctypes function. The class will contain a from_param method which ctypes will use to convert any ndarray passed in to the function to a ctypes-recognized object. In the process, the conversion will perform checking on any properties of the ndarray that were specified by the user in the call to ndpointer. Aspects of the ndarray that can be checked include the data-type, the number-of-dimensions, the shape, and/or the state of the flags on any array passed. The return value of the from_param method is the ctypes attribute of the array which (because it contains the _as_parameter_ attribute pointing to the array data area) can be used by ctypes directly. The ctypes attribute of an ndarray is also endowed with additional attributes that may be convenient when passing additional information about the array into a ctypes function. The attributes data, shape, and strides can provide ctypes compatible types corresponding to the data-area, the shape, and the strides of the array. The data attribute returns a c_void_p representing a pointer to the data area. The shape and strides attributes each return an array of ctypes integers (or None representing a NULL pointer, if a 0-d array). The base ctype of the array is a ctype integer of the same size as a pointer on the platform. There are also methods data_as({ctype}), shape_as(<base ctype>), and strides_as(<base ctype>). These return the data as a ctype object of your choice and the shape/strides arrays using an underlying base type of your choice. For convenience, the ctypeslib module also contains c_intp as a ctypes integer data-type whose size is the same as the size of c_void_p on the platform (its value is None if ctypes is not installed). Calling the function The function is accessed as an attribute of or an item from the loaded shared-library. Thus, if ./mylib.so has a function named cool_function1, it may be accessed either as: lib = numpy.ctypeslib.load_library('mylib','.') func1 = lib.cool_function1 # or equivalently func1 = lib['cool_function1'] In ctypes, the return-value of a function is set to be ‘int’ by default. This behavior can be changed by setting the restype attribute of the function. Use None for the restype if the function has no return value (‘void’): func1.restype = None As previously discussed, you can also set the argtypes attribute of the function in order to have ctypes check the types of the input arguments when the function is called. Use the ndpointer factory function to generate a ready-made class for data-type, shape, and flags checking on your new function. The ndpointer function has the signature ndpointer(dtype=None, ndim=None, shape=None, flags=None) Keyword arguments with the value None are not checked. Specifying a keyword enforces checking of that aspect of the ndarray on conversion to a ctypes-compatible object. The dtype keyword can be any object understood as a data-type object. The ndim keyword should be an integer, and the shape keyword should be an integer or a sequence of integers. The flags keyword specifies the minimal flags that are required on any array passed in. This can be specified as a string of comma separated requirements, an integer indicating the requirement bits OR’d together, or a flags object returned from the flags attribute of an array with the necessary requirements. Using an ndpointer class in the argtypes method can make it significantly safer to call a C function using ctypes and the data- area of an ndarray. You may still want to wrap the function in an additional Python wrapper to make it user-friendly (hiding some obvious arguments and making some arguments output arguments). In this process, the requires function in NumPy may be useful to return the right kind of array from a given input. Complete example In this example, we will demonstrate how the addition function and the filter function implemented previously using the other approaches can be implemented using ctypes. First, the C code which implements the algorithms contains the functions zadd, dadd, sadd, cadd, and dfilter2d. The zadd function is: /* Add arrays of contiguous data */ typedef struct {double real; double imag;} cdouble; typedef struct {float real; float imag;} cfloat; void zadd(cdouble *a, cdouble *b, cdouble *c, long n) { while (n--) { c->real = a->real + b->real; c->imag = a->imag + b->imag; a++; b++; c++; } } with similar code for cadd, dadd, and sadd that handles complex float, double, and float data-types, respectively: void cadd(cfloat *a, cfloat *b, cfloat *c, long n) { while (n--) { c->real = a->real + b->real; c->imag = a->imag + b->imag; a++; b++; c++; } } void dadd(double *a, double *b, double *c, long n) { while (n--) { *c++ = *a++ + *b++; } } void sadd(float *a, float *b, float *c, long n) { while (n--) { *c++ = *a++ + *b++; } } The code.c file also contains the function dfilter2d: /* * Assumes b is contiguous and has strides that are multiples of * sizeof(double) */ void dfilter2d(double *a, double *b, ssize_t *astrides, ssize_t *dims) { ssize_t i, j, M, N, S0, S1; ssize_t r, c, rm1, rp1, cp1, cm1; M = dims[0]; N = dims[1]; S0 = astrides[0]/sizeof(double); S1 = astrides[1]/sizeof(double); for (i = 1; i < M - 1; i++) { r = i*S0; rp1 = r + S0; rm1 = r - S0; for (j = 1; j < N - 1; j++) { c = j*S1; cp1 = j + S1; cm1 = j - S1; b[i*N + j] = a[r + c] + (a[rp1 + c] + a[rm1 + c] + a[r + cp1] + a[r + cm1])*0.5 + (a[rp1 + cp1] + a[rp1 + cm1] + a[rm1 + cp1] + a[rm1 + cp1])*0.25; } } } A possible advantage this code has over the Fortran-equivalent code is that it takes arbitrarily strided (i.e. non-contiguous arrays) and may also run faster depending on the optimization capability of your compiler. But, it is an obviously more complicated than the simple code in filter.f. This code must be compiled into a shared library. On my Linux system this is accomplished using: gcc -o code.so -shared code.c Which creates a shared_library named code.so in the current directory. On Windows don’t forget to either add __declspec(dllexport) in front of void on the line preceding each function definition, or write a code.def file that lists the names of the functions to be exported. A suitable Python interface to this shared library should be constructed. To do this create a file named interface.py with the following lines at the top: __all__ = ['add', 'filter2d'] import numpy as np import os _path = os.path.dirname('__file__') lib = np.ctypeslib.load_library('code', _path) _typedict = {'zadd' : complex, 'sadd' : np.single, 'cadd' : np.csingle, 'dadd' : float} for name in _typedict.keys(): val = getattr(lib, name) val.restype = None _type = _typedict[name] val.argtypes = [np.ctypeslib.ndpointer(_type, flags='aligned, contiguous'), np.ctypeslib.ndpointer(_type, flags='aligned, contiguous'), np.ctypeslib.ndpointer(_type, flags='aligned, contiguous,'\ 'writeable'), np.ctypeslib.c_intp] This code loads the shared library named code.{ext} located in the same path as this file. It then adds a return type of void to the functions contained in the library. It also adds argument checking to the functions in the library so that ndarrays can be passed as the first three arguments along with an integer (large enough to hold a pointer on the platform) as the fourth argument. Setting up the filtering function is similar and allows the filtering function to be called with ndarray arguments as the first two arguments and with pointers to integers (large enough to handle the strides and shape of an ndarray) as the last two arguments.: lib.dfilter2d.restype=None lib.dfilter2d.argtypes = [np.ctypeslib.ndpointer(float, ndim=2, flags='aligned'), np.ctypeslib.ndpointer(float, ndim=2, flags='aligned, contiguous,'\ 'writeable'), ctypes.POINTER(np.ctypeslib.c_intp), ctypes.POINTER(np.ctypeslib.c_intp)] Next, define a simple selection function that chooses which addition function to call in the shared library based on the data-type: def select(dtype): if dtype.char in ['?bBhHf']: return lib.sadd, single elif dtype.char in ['F']: return lib.cadd, csingle elif dtype.char in ['DG']: return lib.zadd, complex else: return lib.dadd, float return func, ntype Finally, the two functions to be exported by the interface can be written simply as: def add(a, b): requires = ['CONTIGUOUS', 'ALIGNED'] a = np.asanyarray(a) func, dtype = select(a.dtype) a = np.require(a, dtype, requires) b = np.require(b, dtype, requires) c = np.empty_like(a) func(a,b,c,a.size) return c and: def filter2d(a): a = np.require(a, float, ['ALIGNED']) b = np.zeros_like(a) lib.dfilter2d(a, b, a.ctypes.strides, a.ctypes.shape) return b Conclusion Using ctypes is a powerful way to connect Python with arbitrary C-code. Its advantages for extending Python include clean separation of C code from Python code no need to learn a new syntax except Python and C allows re-use of C code functionality in shared libraries written for other purposes can be obtained with a simple Python wrapper and search for the library. easy integration with NumPy through the ctypes attribute full argument checking with the ndpointer class factory Its disadvantages include It is difficult to distribute an extension module made using ctypes because of a lack of support for building shared libraries in distutils. You must have shared-libraries of your code (no static libraries). Very little support for C++ code and its different library-calling conventions. You will probably need a C wrapper around C++ code to use with ctypes (or just use Boost.Python instead). Because of the difficulty in distributing an extension module made using ctypes, f2py and Cython are still the easiest ways to extend Python for package creation. However, ctypes is in some cases a useful alternative. This should bring more features to ctypes that should eliminate the difficulty in extending Python and distributing the extension using ctypes. Additional tools you may find useful These tools have been found useful by others using Python and so are included here. They are discussed separately because they are either older ways to do things now handled by f2py, Cython, or ctypes (SWIG, PyFort) or because of a lack of reasonable documentation (SIP, Boost). Links to these methods are not included since the most relevant can be found using Google or some other search engine, and any links provided here would be quickly dated. Do not assume that inclusion in this list means that the package deserves attention. Information about these packages are collected here because many people have found them useful and we’d like to give you as many options as possible for tackling the problem of easily integrating your code. SWIG Simplified Wrapper and Interface Generator (SWIG) is an old and fairly stable method for wrapping C/C++-libraries to a large variety of other languages. It does not specifically understand NumPy arrays but can be made usable with NumPy through the use of typemaps. There are some sample typemaps in the numpy/tools/swig directory under numpy.i together with an example module that makes use of them. SWIG excels at wrapping large C/C++ libraries because it can (almost) parse their headers and auto-produce an interface. Technically, you need to generate a .i file that defines the interface. Often, however, this .i file can be parts of the header itself. The interface usually needs a bit of tweaking to be very useful. This ability to parse C/C++ headers and auto-generate the interface still makes SWIG a useful approach to adding functionalilty from C/C++ into Python, despite the other methods that have emerged that are more targeted to Python. SWIG can actually target extensions for several languages, but the typemaps usually have to be language-specific. Nonetheless, with modifications to the Python-specific typemaps, SWIG can be used to interface a library with other languages such as Perl, Tcl, and Ruby. My experience with SWIG has been generally positive in that it is relatively easy to use and quite powerful. It has been used often before becoming more proficient at writing C-extensions. However, writing custom interfaces with SWIG is often troublesome because it must be done using the concept of typemaps which are not Python specific and are written in a C-like syntax. Therefore, other gluing strategies are preferred and SWIG would be probably considered only to wrap a very-large C/C++ library. Nonetheless, there are others who use SWIG quite happily. SIP SIP is another tool for wrapping C/C++ libraries that is Python specific and appears to have very good support for C++. Riverbank Computing developed SIP in order to create Python bindings to the QT library. An interface file must be written to generate the binding, but the interface file looks a lot like a C/C++ header file. While SIP is not a full C++ parser, it understands quite a bit of C++ syntax as well as its own special directives that allow modification of how the Python binding is accomplished. It also allows the user to define mappings between Python types and C/C++ structures and classes. Boost Python Boost is a repository of C++ libraries and Boost.Python is one of those libraries which provides a concise interface for binding C++ classes and functions to Python. The amazing part of the Boost.Python approach is that it works entirely in pure C++ without introducing a new syntax. Many users of C++ report that Boost.Python makes it possible to combine the best of both worlds in a seamless fashion. Using Boost to wrap simple C-subroutines is usually over-kill. Its primary purpose is to make C++ classes available in Python. So, if you have a set of C++ classes that need to be integrated cleanly into Python, consider learning about and using Boost.Python. PyFort PyFort is a nice tool for wrapping Fortran and Fortran-like C-code into Python with support for Numeric arrays. It was written by Paul Dubois, a distinguished computer scientist and the very first maintainer of Numeric (now retired). It is worth mentioning in the hopes that somebody will update PyFort to work with NumPy arrays as well which now support either Fortran or C-style contiguous arrays.
numpy.user.c-info.python-as-glue
numpy.number.__class_getitem__ method number.__class_getitem__(item, /) Return a parametrized wrapper around the number type. New in version 1.22. Returns aliastypes.GenericAlias A parametrized number type. See also PEP 585 Type hinting generics in standard collections. Notes This method is only available for python 3.9 and later. Examples >>> from typing import Any >>> import numpy as np >>> np.signedinteger[Any] numpy.signedinteger[typing.Any]
numpy.reference.generated.numpy.number.__class_getitem__
numpy.absolute numpy.absolute(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'absolute'> Calculate the absolute value element-wise. np.abs is a shorthand for this function. Parameters xarray_like Input array. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns absolutendarray An ndarray containing the absolute value of each element in x. For complex input, a + ib, the absolute value is \(\sqrt{ a^2 + b^2 }\). This is a scalar if x is a scalar. Examples >>> x = np.array([-1.2, 1.2]) >>> np.absolute(x) array([ 1.2, 1.2]) >>> np.absolute(1.2 + 1j) 1.5620499351813308 Plot the function over [-10, 10]: >>> import matplotlib.pyplot as plt >>> x = np.linspace(start=-10, stop=10, num=101) >>> plt.plot(x, np.absolute(x)) >>> plt.show() Plot the function over the complex plane: >>> xx = x + 1j * x[:, np.newaxis] >>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray') >>> plt.show() The abs function can be used as a shorthand for np.absolute on ndarrays. >>> x = np.array([-1.2, 1.2]) >>> abs(x) array([1.2, 1.2])
numpy.reference.generated.numpy.absolute
numpy.add numpy.add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'add'> Add arguments element-wise. Parameters x1, x2array_like The arrays to be added. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns addndarray or scalar The sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. Notes Equivalent to x1 + x2 in terms of array broadcasting. Examples >>> np.add(1.0, 4.0) 5.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.add(x1, x2) array([[ 0., 2., 4.], [ 3., 5., 7.], [ 6., 8., 10.]]) The + operator can be used as a shorthand for np.add on ndarrays. >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> x1 + x2 array([[ 0., 2., 4.], [ 3., 5., 7.], [ 6., 8., 10.]])
numpy.reference.generated.numpy.add
numpy.all numpy.all(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)[source] Test whether all array elements along a given axis evaluate to True. Parameters aarray_like Input array or object that can be converted to an array. axisNone or int or tuple of ints, optional Axis or axes along which a logical AND reduction is performed. The default (axis=None) is to perform a logical AND over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis. New in version 1.7.0. If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before. outndarray, optional Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved (e.g., if dtype(out) is float, the result will consist of 0.0’s and 1.0’s). See Output type determination for more details. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. wherearray_like of bool, optional Elements to include in checking for all True values. See reduce for details. New in version 1.20.0. Returns allndarray, bool A new boolean or array is returned unless out is specified, in which case a reference to out is returned. See also ndarray.all equivalent method any Test whether any element along a given axis evaluates to True. Notes Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero. Examples >>> np.all([[True,False],[True,True]]) False >>> np.all([[True,False],[True,True]], axis=0) array([ True, False]) >>> np.all([-1, 4, 5]) True >>> np.all([1.0, np.nan]) True >>> np.all([[True, True], [False, True]], where=[[True], [False]]) True >>> o=np.array(False) >>> z=np.all([-1, 4, 5], out=o) >>> id(z), id(o), z (28293632, 28293632, array(True)) # may vary
numpy.reference.generated.numpy.all
numpy.allclose numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)[source] Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b. NaNs are treated as equal if they are in the same place and if equal_nan=True. Infs are treated as equal if they are in the same place and of the same sign in both arrays. Parameters a, barray_like Input arrays to compare. rtolfloat The relative tolerance parameter (see Notes). atolfloat The absolute tolerance parameter (see Notes). equal_nanbool Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array. New in version 1.10.0. Returns allclosebool Returns True if the two arrays are equal within the given tolerance; False otherwise. See also isclose, all, any, equal Notes If the following equation is element-wise True, then allclose returns True. absolute(a - b) <= (atol + rtol * absolute(b)) The above equation is not symmetric in a and b, so that allclose(a, b) might be different from allclose(b, a) in some rare cases. The comparison of a and b uses standard broadcasting, which means that a and b need not have the same shape in order for allclose(a, b) to evaluate to True. The same is true for equal but not array_equal. allclose is not defined for non-numeric data types. bool is considered a numeric data-type for this purpose. Examples >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8]) False >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9]) True >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan]) False >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) True
numpy.reference.generated.numpy.allclose
numpy.amax numpy.amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source] Return the maximum of an array or maximum along an axis. Parameters aarray_like Input data. axisNone or int or tuple of ints, optional Axis or axes along which to operate. By default, flattened input is used. New in version 1.7.0. If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before. outndarray, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See Output type determination for more details. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the amax method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. initialscalar, optional The minimum value of an output element. Must be present to allow computation on empty slice. See reduce for details. New in version 1.15.0. wherearray_like of bool, optional Elements to compare for the maximum. See reduce for details. New in version 1.17.0. Returns amaxndarray or scalar Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. See also amin The minimum value of an array along a given axis, propagating any NaNs. nanmax The maximum value of an array along a given axis, ignoring any NaNs. maximum Element-wise maximum of two arrays, propagating any NaNs. fmax Element-wise maximum of two arrays, ignoring any NaNs. argmax Return the indices of the maximum values. nanmin, minimum, fmin Notes NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmax. Don’t use amax for element-wise comparison of 2 arrays; when a.shape[0] is 2, maximum(a[0], a[1]) is faster than amax(a, axis=0). Examples >>> a = np.arange(4).reshape((2,2)) >>> a array([[0, 1], [2, 3]]) >>> np.amax(a) # Maximum of the flattened array 3 >>> np.amax(a, axis=0) # Maxima along the first axis array([2, 3]) >>> np.amax(a, axis=1) # Maxima along the second axis array([1, 3]) >>> np.amax(a, where=[False, True], initial=-1, axis=0) array([-1, 3]) >>> b = np.arange(5, dtype=float) >>> b[2] = np.NaN >>> np.amax(b) nan >>> np.amax(b, where=~np.isnan(b), initial=-1) 4.0 >>> np.nanmax(b) 4.0 You can use an initial value to compute the maximum of an empty slice, or to initialize it to a different value: >>> np.amax([[-50], [10]], axis=-1, initial=0) array([ 0, 10]) Notice that the initial value is used as one of the elements for which the maximum is determined, unlike for the default argument Python’s max function, which is only used for empty iterables. >>> np.amax([5], initial=6) 6 >>> max([5], default=6) 5
numpy.reference.generated.numpy.amax
numpy.amin numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source] Return the minimum of an array or minimum along an axis. Parameters aarray_like Input data. axisNone or int or tuple of ints, optional Axis or axes along which to operate. By default, flattened input is used. New in version 1.7.0. If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before. outndarray, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See Output type determination for more details. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the amin method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. initialscalar, optional The maximum value of an output element. Must be present to allow computation on empty slice. See reduce for details. New in version 1.15.0. wherearray_like of bool, optional Elements to compare for the minimum. See reduce for details. New in version 1.17.0. Returns aminndarray or scalar Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. See also amax The maximum value of an array along a given axis, propagating any NaNs. nanmin The minimum value of an array along a given axis, ignoring any NaNs. minimum Element-wise minimum of two arrays, propagating any NaNs. fmin Element-wise minimum of two arrays, ignoring any NaNs. argmin Return the indices of the minimum values. nanmax, maximum, fmax Notes NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmin. Don’t use amin for element-wise comparison of 2 arrays; when a.shape[0] is 2, minimum(a[0], a[1]) is faster than amin(a, axis=0). Examples >>> a = np.arange(4).reshape((2,2)) >>> a array([[0, 1], [2, 3]]) >>> np.amin(a) # Minimum of the flattened array 0 >>> np.amin(a, axis=0) # Minima along the first axis array([0, 1]) >>> np.amin(a, axis=1) # Minima along the second axis array([0, 2]) >>> np.amin(a, where=[False, True], initial=10, axis=0) array([10, 1]) >>> b = np.arange(5, dtype=float) >>> b[2] = np.NaN >>> np.amin(b) nan >>> np.amin(b, where=~np.isnan(b), initial=10) 0.0 >>> np.nanmin(b) 0.0 >>> np.amin([[-50], [10]], axis=-1, initial=0) array([-50, 0]) Notice that the initial value is used as one of the elements for which the minimum is determined, unlike for the default argument Python’s max function, which is only used for empty iterables. Notice that this isn’t the same as Python’s default argument. >>> np.amin([6], initial=5) 5 >>> min([6], default=5) 6
numpy.reference.generated.numpy.amin
numpy.angle numpy.angle(z, deg=False)[source] Return the angle of the complex argument. Parameters zarray_like A complex number or sequence of complex numbers. degbool, optional Return angle in degrees if True, radians if False (default). Returns anglendarray or scalar The counterclockwise angle from the positive real axis on the complex plane in the range (-pi, pi], with dtype as numpy.float64. Changed in version 1.16.0: This function works on subclasses of ndarray like ma.array. See also arctan2 absolute Notes Although the angle of the complex number 0 is undefined, numpy.angle(0) returns the value 0. Examples >>> np.angle([1.0, 1.0j, 1+1j]) # in radians array([ 0. , 1.57079633, 0.78539816]) # may vary >>> np.angle(1+1j, deg=True) # in degrees 45.0
numpy.reference.generated.numpy.angle
numpy.any numpy.any(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)[source] Test whether any array element along a given axis evaluates to True. Returns single boolean unless axis is not None Parameters aarray_like Input array or object that can be converted to an array. axisNone or int or tuple of ints, optional Axis or axes along which a logical OR reduction is performed. The default (axis=None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis. New in version 1.7.0. If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before. outndarray, optional Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved (e.g., if it is of type float, then it will remain so, returning 1.0 for True and 0.0 for False, regardless of the type of a). See Output type determination for more details. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the any method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. wherearray_like of bool, optional Elements to include in checking for any True values. See reduce for details. New in version 1.20.0. Returns anybool or ndarray A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned. See also ndarray.any equivalent method all Test whether all elements along a given axis evaluate to True. Notes Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero. Examples >>> np.any([[True, False], [True, True]]) True >>> np.any([[True, False], [False, False]], axis=0) array([ True, False]) >>> np.any([-1, 0, 5]) True >>> np.any(np.nan) True >>> np.any([[True, False], [False, False]], where=[[False], [True]]) False >>> o=np.array(False) >>> z=np.any([-1, 4, 5], out=o) >>> z, o (array(True), array(True)) >>> # Check now that z is a reference to o >>> z is o True >>> id(z), id(o) # identity of z and o (191614240, 191614240)
numpy.reference.generated.numpy.any
numpy.append numpy.append(arr, values, axis=None)[source] Append values to the end of an array. Parameters arrarray_like Values are appended to a copy of this array. valuesarray_like These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use. axisint, optional The axis along which values are appended. If axis is not given, both arr and values are flattened before use. Returns appendndarray A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array. See also insert Insert elements into an array. delete Delete elements from an array. Examples >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) array([1, 2, 3, ..., 7, 8, 9]) When axis is specified, values must have the correct shape. >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0) Traceback (most recent call last): ... ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)
numpy.reference.generated.numpy.append
numpy.apply_along_axis numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)[source] Apply a function to 1-D slices along the given axis. Execute func1d(a, *args, **kwargs) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis. This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii, jj, and kk to a tuple of indices: Ni, Nk = a.shape[:axis], a.shape[axis+1:] for ii in ndindex(Ni): for kk in ndindex(Nk): f = func1d(arr[ii + s_[:,] + kk]) Nj = f.shape for jj in ndindex(Nj): out[ii + jj + kk] = f[jj] Equivalently, eliminating the inner loop, this can be expressed as: Ni, Nk = a.shape[:axis], a.shape[axis+1:] for ii in ndindex(Ni): for kk in ndindex(Nk): out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk]) Parameters func1dfunction (M,) -> (Nj…) This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis. axisinteger Axis along which arr is sliced. arrndarray (Ni…, M, Nk…) Input array. argsany Additional arguments to func1d. kwargsany Additional named arguments to func1d. New in version 1.9.0. Returns outndarray (Ni…, Nj…, Nk…) The output array. The shape of out is identical to the shape of arr, except along the axis dimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of func1d. So if func1d returns a scalar out will have one fewer dimensions than arr. See also apply_over_axes Apply a function repeatedly over multiple axes. Examples >>> def my_func(a): ... """Average first and last element of a 1-D array""" ... return (a[0] + a[-1]) * 0.5 >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(my_func, 0, b) array([4., 5., 6.]) >>> np.apply_along_axis(my_func, 1, b) array([2., 5., 8.]) For a function that returns a 1D array, the number of dimensions in outarr is the same as arr. >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]]) >>> np.apply_along_axis(sorted, 1, b) array([[1, 7, 8], [3, 4, 9], [2, 5, 6]]) For a function that returns a higher dimensional array, those dimensions are inserted in place of the axis dimension. >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(np.diag, -1, b) array([[[1, 0, 0], [0, 2, 0], [0, 0, 3]], [[4, 0, 0], [0, 5, 0], [0, 0, 6]], [[7, 0, 0], [0, 8, 0], [0, 0, 9]]])
numpy.reference.generated.numpy.apply_along_axis
numpy.apply_over_axes numpy.apply_over_axes(func, a, axes)[source] Apply a function repeatedly over multiple axes. func is called as res = func(a, axis), where axis is the first element of axes. The result res of the function call must have either the same dimensions as a or one less dimension. If res has one less dimension than a, a dimension is inserted before axis. The call to func is then repeated for each axis in axes, with res as the first argument. Parameters funcfunction This function must take two arguments, func(a, axis). aarray_like Input array. axesarray_like Axes over which func is applied; the elements must be integers. Returns apply_over_axisndarray The output array. The number of dimensions is the same as a, but the shape can be different. This depends on whether func changes the shape of its output with respect to its input. See also apply_along_axis Apply a function to 1-D slices of an array along the given axis. Notes This function is equivalent to tuple axis arguments to reorderable ufuncs with keepdims=True. Tuple axis arguments to ufuncs have been available since version 1.7.0. Examples >>> a = np.arange(24).reshape(2,3,4) >>> a array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]) Sum over axes 0 and 2. The result has same number of dimensions as the original array: >>> np.apply_over_axes(np.sum, a, [0,2]) array([[[ 60], [ 92], [124]]]) Tuple axis arguments to ufuncs are equivalent: >>> np.sum(a, axis=(0,2), keepdims=True) array([[[ 60], [ 92], [124]]])
numpy.reference.generated.numpy.apply_over_axes
numpy.arange numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None) Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, it is often better to use numpy.linspace. See the warnings section below for more information. Parameters startinteger or real, optional Start of interval. The interval includes this value. The default start value is 0. stopinteger or real End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out. stepinteger or real, optional Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given. dtypedtype The type of the output array. If dtype is not given, infer the data type from the other input arguments. likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns arangendarray Array of evenly spaced values. For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop. Warning The length of the output might not be numerically stable. Another stability issue is due to the internal implementation of numpy.arange. The actual step value used to populate the array is dtype(start + step) - dtype(start) and not step. Precision loss can occur here, due to casting or due to using floating points when start is much larger than step. This can lead to unexpected behaviour. For example: >>> np.arange(0, 5, 0.5, dtype=int) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) >>> np.arange(-3, 3, 0.5, dtype=int) array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) In such cases, the use of numpy.linspace should be preferred. See also numpy.linspace Evenly spaced numbers with careful handling of endpoints. numpy.ogrid Arrays of evenly spaced numbers in N-dimensions. numpy.mgrid Grid-shaped arrays of evenly spaced numbers in N-dimensions. Examples >>> np.arange(3) array([0, 1, 2]) >>> np.arange(3.0) array([ 0., 1., 2.]) >>> np.arange(3,7) array([3, 4, 5, 6]) >>> np.arange(3,7,2) array([3, 5])
numpy.reference.generated.numpy.arange
numpy.arccos numpy.arccos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'arccos'> Trigonometric inverse cosine, element-wise. The inverse of cos so that, if y = cos(x), then x = arccos(y). Parameters xarray_like x-coordinate on the unit circle. For real arguments, the domain is [-1, 1]. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns anglendarray The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar. See also cos, arctan, arcsin, emath.arccos Notes arccos is a multivalued function: for each x there are infinitely many numbers z such that cos(z) = x. The convention is to return the angle z whose real part lies in [0, pi]. For real-valued input data types, arccos always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arccos is a complex analytic function that has branch cuts [-inf, -1] and [1, inf] and is continuous from above on the former and from below on the latter. The inverse cos is also known as acos or cos^-1. References M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 79. https://personal.math.ubc.ca/~cbm/aands/page_79.htm Examples We expect the arccos of 1 to be 0, and of -1 to be pi: >>> np.arccos([1, -1]) array([ 0. , 3.14159265]) Plot arccos: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-1, 1, num=100) >>> plt.plot(x, np.arccos(x)) >>> plt.axis('tight') >>> plt.show()
numpy.reference.generated.numpy.arccos
numpy.arccosh numpy.arccosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'arccosh'> Inverse hyperbolic cosine, element-wise. Parameters xarray_like Input array. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns arccoshndarray Array of the same shape as x. This is a scalar if x is a scalar. See also cosh, arcsinh, sinh, arctanh, tanh Notes arccosh is a multivalued function: for each x there are infinitely many numbers z such that cosh(z) = x. The convention is to return the z whose imaginary part lies in [-pi, pi] and the real part in [0, inf]. For real-valued input data types, arccosh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arccosh is a complex analytical function that has a branch cut [-inf, 1] and is continuous from above on it. References 1 M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 86. https://personal.math.ubc.ca/~cbm/aands/page_86.htm 2 Wikipedia, “Inverse hyperbolic function”, https://en.wikipedia.org/wiki/Arccosh Examples >>> np.arccosh([np.e, 10.0]) array([ 1.65745445, 2.99322285]) >>> np.arccosh(1) 0.0
numpy.reference.generated.numpy.arccosh
numpy.arcsin numpy.arcsin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'arcsin'> Inverse sine, element-wise. Parameters xarray_like y-coordinate on the unit circle. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns anglendarray The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar. See also sin, cos, arccos, tan, arctan, arctan2, emath.arcsin Notes arcsin is a multivalued function: for each x there are infinitely many numbers z such that \(sin(z) = x\). The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. For real-valued input data types, arcsin always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arcsin is a complex analytic function that has, by convention, the branch cuts [-inf, -1] and [1, inf] and is continuous from above on the former and from below on the latter. The inverse sine is also known as asin or sin^{-1}. References Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79ff. https://personal.math.ubc.ca/~cbm/aands/page_79.htm Examples >>> np.arcsin(1) # pi/2 1.5707963267948966 >>> np.arcsin(-1) # -pi/2 -1.5707963267948966 >>> np.arcsin(0) 0.0
numpy.reference.generated.numpy.arcsin
numpy.arcsinh numpy.arcsinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'arcsinh'> Inverse hyperbolic sine element-wise. Parameters xarray_like Input array. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar Array of the same shape as x. This is a scalar if x is a scalar. Notes arcsinh is a multivalued function: for each x there are infinitely many numbers z such that sinh(z) = x. The convention is to return the z whose imaginary part lies in [-pi/2, pi/2]. For real-valued input data types, arcsinh always returns real output. For each value that cannot be expressed as a real number or infinity, it returns nan and sets the invalid floating point error flag. For complex-valued input, arccos is a complex analytical function that has branch cuts [1j, infj] and [-1j, -infj] and is continuous from the right on the former and from the left on the latter. The inverse hyperbolic sine is also known as asinh or sinh^-1. References 1 M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 86. https://personal.math.ubc.ca/~cbm/aands/page_86.htm 2 Wikipedia, “Inverse hyperbolic function”, https://en.wikipedia.org/wiki/Arcsinh Examples >>> np.arcsinh(np.array([np.e, 10.0])) array([ 1.72538256, 2.99822295])
numpy.reference.generated.numpy.arcsinh
numpy.arctan numpy.arctan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'arctan'> Trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = arctan(y). Parameters xarray_like outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar Out has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar. See also arctan2 The “four quadrant” arctan of the angle formed by (x, y) and the positive x-axis. angle Argument of complex values. Notes arctan is a multi-valued function: for each x there are infinitely many numbers z such that tan(z) = x. The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. For real-valued input data types, arctan always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arctan is a complex analytic function that has [1j, infj] and [-1j, -infj] as branch cuts, and is continuous from the left on the former and from the right on the latter. The inverse tangent is also known as atan or tan^{-1}. References Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79. https://personal.math.ubc.ca/~cbm/aands/page_79.htm Examples We expect the arctan of 0 to be 0, and of 1 to be pi/4: >>> np.arctan([0, 1]) array([ 0. , 0.78539816]) >>> np.pi/4 0.78539816339744828 Plot arctan: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-10, 10) >>> plt.plot(x, np.arctan(x)) >>> plt.axis('tight') >>> plt.show()
numpy.reference.generated.numpy.arctan
numpy.arctan2 numpy.arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'arctan2'> Element-wise arc tangent of x1/x2 choosing the quadrant correctly. The quadrant (i.e., branch) is chosen so that arctan2(x1, x2) is the signed angle in radians between the ray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing through the point (x2, x1). (Note the role reversal: the “y-coordinate” is the first function parameter, the “x-coordinate” is the second.) By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf (see Notes for specific values). This function is not defined for complex-valued arguments; for the so-called argument of complex values, use angle. Parameters x1array_like, real-valued y-coordinates. x2array_like, real-valued x-coordinates. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns anglendarray Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars. See also arctan, tan, angle Notes arctan2 is identical to the atan2 function of the underlying C library. The following special values are defined in the C standard: [1] x1 x2 arctan2(x1,x2) +/- 0 +0 +/- 0 +/- 0 -0 +/- pi > 0 +/-inf +0 / +pi < 0 +/-inf -0 / -pi +/-inf +inf +/- (pi/4) +/-inf -inf +/- (3*pi/4) Note that +0 and -0 are distinct floating point numbers, as are +inf and -inf. References 1 ISO/IEC standard 9899:1999, “Programming language C.” Examples Consider four points in different quadrants: >>> x = np.array([-1, +1, +1, -1]) >>> y = np.array([-1, -1, +1, +1]) >>> np.arctan2(y, x) * 180 / np.pi array([-135., -45., 45., 135.]) Note the order of the parameters. arctan2 is defined also when x2 = 0 and at several other special points, obtaining values in the range [-pi, pi]: >>> np.arctan2([1., -1.], [0., 0.]) array([ 1.57079633, -1.57079633]) >>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf]) array([ 0. , 3.14159265, 0.78539816])
numpy.reference.generated.numpy.arctan2
numpy.arctanh numpy.arctanh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'arctanh'> Inverse hyperbolic tangent element-wise. Parameters xarray_like Input array. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar Array of the same shape as x. This is a scalar if x is a scalar. See also emath.arctanh Notes arctanh is a multivalued function: for each x there are infinitely many numbers z such that tanh(z) = x. The convention is to return the z whose imaginary part lies in [-pi/2, pi/2]. For real-valued input data types, arctanh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arctanh is a complex analytical function that has branch cuts [-1, -inf] and [1, inf] and is continuous from above on the former and from below on the latter. The inverse hyperbolic tangent is also known as atanh or tanh^-1. References 1 M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 86. https://personal.math.ubc.ca/~cbm/aands/page_86.htm 2 Wikipedia, “Inverse hyperbolic function”, https://en.wikipedia.org/wiki/Arctanh Examples >>> np.arctanh([0, -0.5]) array([ 0. , -0.54930614])
numpy.reference.generated.numpy.arctanh
numpy.argmax numpy.argmax(a, axis=None, out=None, *, keepdims=<no value>)[source] Returns the indices of the maximum values along an axis. Parameters aarray_like Input array. axisint, optional By default, the index is into the flattened array, otherwise along the specified axis. outarray, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. New in version 1.22.0. Returns index_arrayndarray of ints Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. If keepdims is set to True, then the size of axis will be 1 with the resulting array having same shape as a.shape. See also ndarray.argmax, argmin amax The maximum value along a given axis. unravel_index Convert a flat index into an index tuple. take_along_axis Apply np.expand_dims(index_array, axis) from argmax to an array as if by calling max. Notes In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned. Examples >>> a = np.arange(6).reshape(2,3) + 10 >>> a array([[10, 11, 12], [13, 14, 15]]) >>> np.argmax(a) 5 >>> np.argmax(a, axis=0) array([1, 1, 1]) >>> np.argmax(a, axis=1) array([2, 2]) Indexes of the maximal elements of a N-dimensional array: >>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape) >>> ind (1, 2) >>> a[ind] 15 >>> b = np.arange(6) >>> b[1] = 5 >>> b array([0, 5, 2, 3, 4, 5]) >>> np.argmax(b) # Only the first occurrence is returned. 1 >>> x = np.array([[4,2,3], [1,0,3]]) >>> index_array = np.argmax(x, axis=-1) >>> # Same as np.amax(x, axis=-1, keepdims=True) >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1) array([[4], [3]]) >>> # Same as np.amax(x, axis=-1) >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1) array([4, 3]) Setting keepdims to True, >>> x = np.arange(24).reshape((2, 3, 4)) >>> res = np.argmax(x, axis=1, keepdims=True) >>> res.shape (2, 1, 4)
numpy.reference.generated.numpy.argmax
numpy.argmin numpy.argmin(a, axis=None, out=None, *, keepdims=<no value>)[source] Returns the indices of the minimum values along an axis. Parameters aarray_like Input array. axisint, optional By default, the index is into the flattened array, otherwise along the specified axis. outarray, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array. New in version 1.22.0. Returns index_arrayndarray of ints Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. If keepdims is set to True, then the size of axis will be 1 with the resulting array having same shape as a.shape. See also ndarray.argmin, argmax amin The minimum value along a given axis. unravel_index Convert a flat index into an index tuple. take_along_axis Apply np.expand_dims(index_array, axis) from argmin to an array as if by calling min. Notes In case of multiple occurrences of the minimum values, the indices corresponding to the first occurrence are returned. Examples >>> a = np.arange(6).reshape(2,3) + 10 >>> a array([[10, 11, 12], [13, 14, 15]]) >>> np.argmin(a) 0 >>> np.argmin(a, axis=0) array([0, 0, 0]) >>> np.argmin(a, axis=1) array([0, 0]) Indices of the minimum elements of a N-dimensional array: >>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape) >>> ind (0, 0) >>> a[ind] 10 >>> b = np.arange(6) + 10 >>> b[4] = 10 >>> b array([10, 11, 12, 13, 10, 15]) >>> np.argmin(b) # Only the first occurrence is returned. 0 >>> x = np.array([[4,2,3], [1,0,3]]) >>> index_array = np.argmin(x, axis=-1) >>> # Same as np.amin(x, axis=-1, keepdims=True) >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1) array([[2], [0]]) >>> # Same as np.amax(x, axis=-1) >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1) array([2, 0]) Setting keepdims to True, >>> x = np.arange(24).reshape((2, 3, 4)) >>> res = np.argmin(x, axis=1, keepdims=True) >>> res.shape (2, 1, 4)
numpy.reference.generated.numpy.argmin
numpy.argpartition numpy.argpartition(a, kth, axis=- 1, kind='introselect', order=None)[source] Perform an indirect partition along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in partitioned order. New in version 1.8.0. Parameters aarray_like Array to sort. kthint or sequence of ints Element index to partition by. The k-th element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all of them into their sorted position at once. Deprecated since version 1.22.0: Passing booleans as index is deprecated. axisint or None, optional Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used. kind{‘introselect’}, optional Selection algorithm. Default is ‘introselect’ orderstr or list of str, optional When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. Returns index_arrayndarray, int Array of indices that partition a along the specified axis. If a is one-dimensional, a[index_array] yields a partitioned a. More generally, np.take_along_axis(a, index_array, axis=a) always yields the partitioned a, irrespective of dimensionality. See also partition Describes partition algorithms used. ndarray.partition Inplace partition. argsort Full indirect sort. take_along_axis Apply index_array from argpartition to an array as if by calling partition. Notes See partition for notes on the different selection algorithms. Examples One dimensional array: >>> x = np.array([3, 4, 2, 1]) >>> x[np.argpartition(x, 3)] array([2, 1, 3, 4]) >>> x[np.argpartition(x, (1, 3))] array([1, 2, 3, 4]) >>> x = [3, 4, 2, 1] >>> np.array(x)[np.argpartition(x, 3)] array([2, 1, 3, 4]) Multi-dimensional array: >>> x = np.array([[3, 4, 2], [1, 3, 1]]) >>> index_array = np.argpartition(x, kth=1, axis=-1) >>> np.take_along_axis(x, index_array, axis=-1) # same as np.partition(x, kth=1) array([[2, 3, 4], [1, 1, 3]])
numpy.reference.generated.numpy.argpartition
numpy.argsort numpy.argsort(a, axis=- 1, kind=None, order=None)[source] Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order. Parameters aarray_like Array to sort. axisint or None, optional Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used. kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility. Changed in version 1.15.0.: The ‘stable’ option was added. orderstr or list of str, optional When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. Returns index_arrayndarray, int Array of indices that sort a along the specified axis. If a is one-dimensional, a[index_array] yields a sorted a. More generally, np.take_along_axis(a, index_array, axis=axis) always yields the sorted a, irrespective of dimensionality. See also sort Describes sorting algorithms used. lexsort Indirect stable sort with multiple keys. ndarray.sort Inplace sort. argpartition Indirect partial sort. take_along_axis Apply index_array from argsort to an array as if by calling sort. Notes See sort for notes on the different sorting algorithms. As of NumPy 1.4.0 argsort works with real/complex arrays containing nan values. The enhanced sort order is documented in sort. Examples One dimensional array: >>> x = np.array([3, 1, 2]) >>> np.argsort(x) array([1, 2, 0]) Two-dimensional array: >>> x = np.array([[0, 3], [2, 2]]) >>> x array([[0, 3], [2, 2]]) >>> ind = np.argsort(x, axis=0) # sorts along first axis (down) >>> ind array([[0, 1], [1, 0]]) >>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0) array([[0, 2], [2, 3]]) >>> ind = np.argsort(x, axis=1) # sorts along last axis (across) >>> ind array([[0, 1], [0, 1]]) >>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1) array([[0, 3], [2, 2]]) Indices of the sorted elements of a N-dimensional array: >>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape) >>> ind (array([0, 1, 1, 0]), array([0, 0, 1, 1])) >>> x[ind] # same as np.sort(x, axis=None) array([0, 2, 2, 3]) Sorting with keys: >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')]) >>> x array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')]) >>> np.argsort(x, order=('x','y')) array([1, 0]) >>> np.argsort(x, order=('y','x')) array([0, 1])
numpy.reference.generated.numpy.argsort
numpy.argwhere numpy.argwhere(a)[source] Find the indices of array elements that are non-zero, grouped by element. Parameters aarray_like Input data. Returns index_array(N, a.ndim) ndarray Indices of elements that are non-zero. Indices are grouped by element. This array will have shape (N, a.ndim) where N is the number of non-zero items. See also where, nonzero Notes np.argwhere(a) is almost the same as np.transpose(np.nonzero(a)), but produces a result of the correct shape for a 0D array. The output of argwhere is not suitable for indexing arrays. For this purpose use nonzero(a) instead. Examples >>> x = np.arange(6).reshape(2,3) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.argwhere(x>1) array([[0, 2], [1, 0], [1, 1], [1, 2]])
numpy.reference.generated.numpy.argwhere
numpy.around numpy.around(a, decimals=0, out=None)[source] Evenly round to the given number of decimals. Parameters aarray_like Input data. decimalsint, optional Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point. outndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. See Output type determination for more details. Returns rounded_arrayndarray An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float. See also ndarray.round equivalent method ceil, fix, floor, rint, trunc Notes For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. np.around uses a fast but sometimes inexact algorithm to round floating-point datatypes. For positive decimals it is equivalent to np.true_divide(np.rint(a * 10**decimals), 10**decimals), which has error due to the inexact representation of decimal fractions in the IEEE floating point standard [1] and errors introduced when scaling by powers of ten. For instance, note the extra “1” in the following: >>> np.round(56294995342131.5, 3) 56294995342131.51 If your goal is to print such values with a fixed number of decimals, it is preferable to use numpy’s float printing routines to limit the number of printed decimals: >>> np.format_float_positional(56294995342131.5, precision=3) '56294995342131.5' The float printing routines use an accurate but much more computationally demanding algorithm to compute the number of digits after the decimal point. Alternatively, Python’s builtin round function uses a more accurate but slower algorithm for 64-bit floating point values: >>> round(56294995342131.5, 3) 56294995342131.5 >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997 (16.06, 16.05) References 1 “Lecture Notes on the Status of IEEE 754”, William Kahan, https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF Examples >>> np.around([0.37, 1.64]) array([0., 2.]) >>> np.around([0.37, 1.64], decimals=1) array([0.4, 1.6]) >>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value array([0., 2., 2., 4., 4.]) >>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned array([ 1, 2, 3, 11]) >>> np.around([1,2,3,11], decimals=-1) array([ 0, 0, 0, 10])
numpy.reference.generated.numpy.around
numpy.array numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None) Create an array. Parameters objectarray_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. If object is a scalar, a 0-dimensional array containing object is returned. dtypedata-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. copybool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.). order{‘K’, ‘A’, ‘C’, ‘F’}, optional Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds. order no copy copy=True ‘K’ unchanged F & C order preserved, otherwise most similar order ‘A’ unchanged F order if input is F and not C, otherwise C order ‘C’ C order C order ‘F’ F order F order When copy=False and a copy is made for other reasons, the result is the same as if copy=True, with some exceptions for ‘A’, see the Notes section. The default order is ‘K’. subokbool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). ndminint, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement. likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns outndarray An array object satisfying the specified requirements. See also empty_like Return an empty array with shape and type of input. ones_like Return an array of ones with shape and type of input. zeros_like Return an array of zeros with shape and type of input. full_like Return a new array with shape of input filled with value. empty Return a new uninitialized array. ones Return a new array setting values to one. zeros Return a new array setting values to zero. full Return a new array of given shape filled with value. Notes When order is ‘A’ and object is an array in neither ‘C’ nor ‘F’ order, and a copy is forced by a change in dtype, then the order of the result is not necessarily ‘C’ as expected. This is likely a bug. Examples >>> np.array([1, 2, 3]) array([1, 2, 3]) Upcasting: >>> np.array([1, 2, 3.0]) array([ 1., 2., 3.]) More than one dimension: >>> np.array([[1, 2], [3, 4]]) array([[1, 2], [3, 4]]) Minimum dimensions 2: >>> np.array([1, 2, 3], ndmin=2) array([[1, 2, 3]]) Type provided: >>> np.array([1, 2, 3], dtype=complex) array([ 1.+0.j, 2.+0.j, 3.+0.j]) Data-type consisting of more than one element: >>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')]) >>> x['a'] array([1, 3]) Creating an array from sub-classes: >>> np.array(np.mat('1 2; 3 4')) array([[1, 2], [3, 4]]) >>> np.array(np.mat('1 2; 3 4'), subok=True) matrix([[1, 2], [3, 4]])
numpy.reference.generated.numpy.array
numpy.array2string numpy.array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix='', style=<no value>, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix='', *, legacy=None)[source] Return a string representation of an array. Parameters andarray Input array. max_line_widthint, optional Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth']. precisionint or None, optional Floating point precision. Defaults to numpy.get_printoptions()['precision']. suppress_smallbool, optional Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress']. separatorstr, optional Inserted between elements. prefixstr, optional suffixstr, optional The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as: prefix + array2string(a) + suffix The output is left-padded by the length of the prefix string, and wrapping is forced at the column max_line_width - len(suffix). It should be noted that the content of prefix and suffix strings are not included in the output. style_NoValue, optional Has no effect, do not use. Deprecated since version 1.14.0. formatterdict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: ‘bool’ ‘int’ ‘timedelta’ : a numpy.timedelta64 ‘datetime’ : a numpy.datetime64 ‘float’ ‘longfloat’ : 128-bit floats ‘complexfloat’ ‘longcomplexfloat’ : composed of two 128-bit floats ‘void’ : type numpy.void ‘numpystr’ : types numpy.string_ and numpy.unicode_ Other keys that can be used to set a group of types at once are: ‘all’ : sets all types ‘int_kind’ : sets ‘int’ ‘float_kind’ : sets ‘float’ and ‘longfloat’ ‘complex_kind’ : sets ‘complexfloat’ and ‘longcomplexfloat’ ‘str_kind’ : sets ‘numpystr’ thresholdint, optional Total number of array elements which trigger summarization rather than full repr. Defaults to numpy.get_printoptions()['threshold']. edgeitemsint, optional Number of array items in summary at beginning and end of each dimension. Defaults to numpy.get_printoptions()['edgeitems']. signstring, either ‘-’, ‘+’, or ‘ ‘, optional Controls printing of the sign of floating-point types. If ‘+’, always print the sign of positive values. If ‘ ‘, always prints a space (whitespace character) in the sign position of positive values. If ‘-’, omit the sign character of positive values. Defaults to numpy.get_printoptions()['sign']. floatmodestr, optional Controls the interpretation of the precision option for floating-point types. Defaults to numpy.get_printoptions()['floatmode']. Can take the following values: ‘fixed’: Always print exactly precision fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. ‘unique’: Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the precision option is ignored. ‘maxprec’: Print at most precision fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. ‘maxprec_equal’: Print at most precision fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements. legacystring or False, optional If set to the string ‘1.13’ enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to False, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. New in version 1.14.0. Returns array_strstr String representation of the array. Raises TypeError if a callable in formatter does not return a string. See also array_str, array_repr, set_printoptions, get_printoptions Notes If a formatter is specified for a certain type, the precision keyword is ignored for that type. This is a very flexible function; array_repr and array_str are using array2string internally so keywords with the same name should work identically in all three functions. Examples >>> x = np.array([1e-16,1,2,3]) >>> np.array2string(x, precision=2, separator=',', ... suppress_small=True) '[0.,1.,2.,3.]' >>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]' >>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0 0x1 0x2]'
numpy.reference.generated.numpy.array2string
numpy.array_equal numpy.array_equal(a1, a2, equal_nan=False)[source] True if two arrays have the same shape and elements, False otherwise. Parameters a1, a2array_like Input arrays. equal_nanbool Whether to compare NaN’s as equal. If the dtype of a1 and a2 is complex, values will be considered equal if either the real or the imaginary component of a given value is nan. New in version 1.19.0. Returns bbool Returns True if the arrays are equal. See also allclose Returns True if two arrays are element-wise equal within a tolerance. array_equiv Returns True if input arrays are shape consistent and all elements equal. Examples >>> np.array_equal([1, 2], [1, 2]) True >>> np.array_equal(np.array([1, 2]), np.array([1, 2])) True >>> np.array_equal([1, 2], [1, 2, 3]) False >>> np.array_equal([1, 2], [1, 4]) False >>> a = np.array([1, np.nan]) >>> np.array_equal(a, a) False >>> np.array_equal(a, a, equal_nan=True) True When equal_nan is True, complex values with nan components are considered equal if either the real or the imaginary components are nan. >>> a = np.array([1 + 1j]) >>> b = a.copy() >>> a.real = np.nan >>> b.imag = np.nan >>> np.array_equal(a, b, equal_nan=True) True
numpy.reference.generated.numpy.array_equal
numpy.array_equiv numpy.array_equiv(a1, a2)[source] Returns True if input arrays are shape consistent and all elements equal. Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one. Parameters a1, a2array_like Input arrays. Returns outbool True if equivalent, False otherwise. Examples >>> np.array_equiv([1, 2], [1, 2]) True >>> np.array_equiv([1, 2], [1, 3]) False Showing the shape equivalence: >>> np.array_equiv([1, 2], [[1, 2], [1, 2]]) True >>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]]) False >>> np.array_equiv([1, 2], [[1, 2], [1, 3]]) False
numpy.reference.generated.numpy.array_equiv
numpy.array_repr numpy.array_repr(arr, max_line_width=None, precision=None, suppress_small=None)[source] Return the string representation of an array. Parameters arrndarray Input array. max_line_widthint, optional Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth']. precisionint, optional Floating point precision. Defaults to numpy.get_printoptions()['precision']. suppress_smallbool, optional Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress']. Returns stringstr The string representation of an array. See also array_str, array2string, set_printoptions Examples >>> np.array_repr(np.array([1,2])) 'array([1, 2])' >>> np.array_repr(np.ma.array([0.])) 'MaskedArray([0.])' >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)' >>> x = np.array([1e-6, 4e-7, 2, 3]) >>> np.array_repr(x, precision=6, suppress_small=True) 'array([0.000001, 0. , 2. , 3. ])'
numpy.reference.generated.numpy.array_repr
numpy.array_split numpy.array_split(ary, indices_or_sections, axis=0)[source] Split an array into multiple sub-arrays. Please refer to the split documentation. The only difference between these functions is that array_split allows indices_or_sections to be an integer that does not equally divide the axis. For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n. See also split Split array into multiple sub-arrays of equal size. Examples >>> x = np.arange(8.0) >>> np.array_split(x, 3) [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])] >>> x = np.arange(9) >>> np.array_split(x, 4) [array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]
numpy.reference.generated.numpy.array_split
numpy.array_str numpy.array_str(a, max_line_width=None, precision=None, suppress_small=None)[source] Return a string representation of the data in an array. The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type. Parameters andarray Input array. max_line_widthint, optional Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth']. precisionint, optional Floating point precision. Defaults to numpy.get_printoptions()['precision']. suppress_smallbool, optional Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress']. See also array2string, array_repr, set_printoptions Examples >>> np.array_str(np.arange(3)) '[0 1 2]'
numpy.reference.generated.numpy.array_str
numpy.asanyarray numpy.asanyarray(a, dtype=None, order=None, *, like=None) Convert the input to an ndarray, but pass ndarray subclasses through. Parameters aarray_like Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays. dtypedata-type, optional By default, the data-type is inferred from the input data. order{‘C’, ‘F’, ‘A’, ‘K’}, optional Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘C’. likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns outndarray or an ndarray subclass Array interpretation of a. If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed. See also asarray Similar function which always returns ndarrays. ascontiguousarray Convert input to a contiguous array. asfarray Convert input to a floating point ndarray. asfortranarray Convert input to an ndarray with column-major memory order. asarray_chkfinite Similar function which checks input for NaNs and Infs. fromiter Create an array from an iterator. fromfunction Construct an array by executing a function on grid positions. Examples Convert a list into an array: >>> a = [1, 2] >>> np.asanyarray(a) array([1, 2]) Instances of ndarray subclasses are passed through as-is: >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) >>> np.asanyarray(a) is a True
numpy.reference.generated.numpy.asanyarray
numpy.asarray numpy.asarray(a, dtype=None, order=None, *, like=None) Convert the input to an array. Parameters aarray_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. dtypedata-type, optional By default, the data-type is inferred from the input data. order{‘C’, ‘F’, ‘A’, ‘K’}, optional Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘K’. likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns outndarray Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned. See also asanyarray Similar function which passes through subclasses. ascontiguousarray Convert input to a contiguous array. asfarray Convert input to a floating point ndarray. asfortranarray Convert input to an ndarray with column-major memory order. asarray_chkfinite Similar function which checks input for NaNs and Infs. fromiter Create an array from an iterator. fromfunction Construct an array by executing a function on grid positions. Examples Convert a list into an array: >>> a = [1, 2] >>> np.asarray(a) array([1, 2]) Existing arrays are not copied: >>> a = np.array([1, 2]) >>> np.asarray(a) is a True If dtype is set, array is copied only if dtype does not match: >>> a = np.array([1, 2], dtype=np.float32) >>> np.asarray(a, dtype=np.float32) is a True >>> np.asarray(a, dtype=np.float64) is a False Contrary to asanyarray, ndarray subclasses are not passed through: >>> issubclass(np.recarray, np.ndarray) True >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) >>> np.asarray(a) is a False >>> np.asanyarray(a) is a True
numpy.reference.generated.numpy.asarray
numpy.asarray_chkfinite numpy.asarray_chkfinite(a, dtype=None, order=None)[source] Convert the input to an array, checking for NaNs or Infs. Parameters aarray_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Success requires no NaNs or Infs. dtypedata-type, optional By default, the data-type is inferred from the input data. order{‘C’, ‘F’, ‘A’, ‘K’}, optional Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘C’. Returns outndarray Array interpretation of a. No copy is performed if the input is already an ndarray. If a is a subclass of ndarray, a base class ndarray is returned. Raises ValueError Raises ValueError if a contains NaN (Not a Number) or Inf (Infinity). See also asarray Create and array. asanyarray Similar function which passes through subclasses. ascontiguousarray Convert input to a contiguous array. asfarray Convert input to a floating point ndarray. asfortranarray Convert input to an ndarray with column-major memory order. fromiter Create an array from an iterator. fromfunction Construct an array by executing a function on grid positions. Examples Convert a list into an array. If all elements are finite asarray_chkfinite is identical to asarray. >>> a = [1, 2] >>> np.asarray_chkfinite(a, dtype=float) array([1., 2.]) Raises ValueError if array_like contains Nans or Infs. >>> a = [1, 2, np.inf] >>> try: ... np.asarray_chkfinite(a) ... except ValueError: ... print('ValueError') ... ValueError
numpy.reference.generated.numpy.asarray_chkfinite
numpy.ascontiguousarray numpy.ascontiguousarray(a, dtype=None, *, like=None) Return a contiguous array (ndim >= 1) in memory (C order). Parameters aarray_like Input array. dtypestr or dtype object, optional Data-type of returned array. likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns outndarray Contiguous array of same shape and content as a, with type dtype if specified. See also asfortranarray Convert input to an ndarray with column-major memory order. require Return an ndarray that satisfies requirements. ndarray.flags Information about the memory layout of the array. Examples >>> x = np.arange(6).reshape(2,3) >>> np.ascontiguousarray(x, dtype=np.float32) array([[0., 1., 2.], [3., 4., 5.]], dtype=float32) >>> x.flags['C_CONTIGUOUS'] True Note: This function returns an array with at least one-dimension (1-d) so it will not preserve 0-d arrays.
numpy.reference.generated.numpy.ascontiguousarray
numpy.asfarray numpy.asfarray(a, dtype=<class 'numpy.double'>)[source] Return an array converted to a float type. Parameters aarray_like The input array. dtypestr or dtype object, optional Float type code to coerce input array a. If dtype is one of the ‘int’ dtypes, it is replaced with float64. Returns outndarray The input a as a float ndarray. Examples >>> np.asfarray([2, 3]) array([2., 3.]) >>> np.asfarray([2, 3], dtype='float') array([2., 3.]) >>> np.asfarray([2, 3], dtype='int8') array([2., 3.])
numpy.reference.generated.numpy.asfarray
numpy.asfortranarray numpy.asfortranarray(a, dtype=None, *, like=None) Return an array (ndim >= 1) laid out in Fortran order in memory. Parameters aarray_like Input array. dtypestr or dtype object, optional By default, the data-type is inferred from the input data. likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns outndarray The input a in Fortran, or column-major, order. See also ascontiguousarray Convert input to a contiguous (C order) array. asanyarray Convert input to an ndarray with either row or column-major memory order. require Return an ndarray that satisfies requirements. ndarray.flags Information about the memory layout of the array. Examples >>> x = np.arange(6).reshape(2,3) >>> y = np.asfortranarray(x) >>> x.flags['F_CONTIGUOUS'] False >>> y.flags['F_CONTIGUOUS'] True Note: This function returns an array with at least one-dimension (1-d) so it will not preserve 0-d arrays.
numpy.reference.generated.numpy.asfortranarray
numpy.asmatrix numpy.asmatrix(data, dtype=None)[source] Interpret the input as a matrix. Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to matrix(data, copy=False). Parameters dataarray_like Input data. dtypedata-type Data-type of the output matrix. Returns matmatrix data interpreted as a matrix. Examples >>> x = np.array([[1, 2], [3, 4]]) >>> m = np.asmatrix(x) >>> x[0,0] = 5 >>> m matrix([[5, 2], [3, 4]])
numpy.reference.generated.numpy.asmatrix
numpy.asscalar numpy.asscalar(a)[source] Convert an array of size 1 to its scalar equivalent. Deprecated since version 1.16: Deprecated, use numpy.ndarray.item() instead. Parameters andarray Input array of size 1. Returns outscalar Scalar representation of a. The output data type is the same type returned by the input’s item method. Examples >>> np.asscalar(np.array([24])) 24
numpy.reference.generated.numpy.asscalar
numpy.atleast_1d numpy.atleast_1d(*arys)[source] Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. Parameters arys1, arys2, …array_like One or more input arrays. Returns retndarray An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary. See also atleast_2d, atleast_3d Examples >>> np.atleast_1d(1.0) array([1.]) >>> x = np.arange(9.0).reshape(3,3) >>> np.atleast_1d(x) array([[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]) >>> np.atleast_1d(x) is x True >>> np.atleast_1d(1, [3, 4]) [array([1]), array([3, 4])]
numpy.reference.generated.numpy.atleast_1d
numpy.atleast_2d numpy.atleast_2d(*arys)[source] View inputs as arrays with at least two dimensions. Parameters arys1, arys2, …array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved. Returns res, res2, …ndarray An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned. See also atleast_1d, atleast_3d Examples >>> np.atleast_2d(3.0) array([[3.]]) >>> x = np.arange(3.0) >>> np.atleast_2d(x) array([[0., 1., 2.]]) >>> np.atleast_2d(x).base is x True >>> np.atleast_2d(1, [1, 2], [[1, 2]]) [array([[1]]), array([[1, 2]]), array([[1, 2]])]
numpy.reference.generated.numpy.atleast_2d
numpy.atleast_3d numpy.atleast_3d(*arys)[source] View inputs as arrays with at least three dimensions. Parameters arys1, arys2, …array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns res1, res2, …ndarray An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1). See also atleast_1d, atleast_2d Examples >>> np.atleast_3d(3.0) array([[[3.]]]) >>> x = np.arange(3.0) >>> np.atleast_3d(x).shape (1, 3, 1) >>> x = np.arange(12.0).reshape(4,3) >>> np.atleast_3d(x).shape (4, 3, 1) >>> np.atleast_3d(x).base is x.base # x is a reshape, so not base itself True >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]): ... print(arr, arr.shape) ... [[[1] [2]]] (1, 2, 1) [[[1] [2]]] (1, 2, 1) [[[1 2]]] (1, 1, 2)
numpy.reference.generated.numpy.atleast_3d
numpy.average numpy.average(a, axis=None, weights=None, returned=False)[source] Compute the weighted average along the specified axis. Parameters aarray_like Array containing data to be averaged. If a is not an array, a conversion is attempted. axisNone or int or tuple of ints, optional Axis or axes along which to average a. The default, axis=None, will average over all of the elements of the input array. If axis is negative it counts from the last to the first axis. New in version 1.7.0. If axis is a tuple of ints, averaging is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. weightsarray_like, optional An array of weights associated with the values in a. Each value in a contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of a along the given axis) or of the same shape as a. If weights=None, then all data in a are assumed to have a weight equal to one. The 1-D calculation is: avg = sum(a * weights) / sum(weights) The only constraint on weights is that sum(weights) must not be 0. returnedbool, optional Default is False. If True, the tuple (average, sum_of_weights) is returned, otherwise only the average is returned. If weights=None, sum_of_weights is equivalent to the number of elements over which the average is taken. Returns retval, [sum_of_weights]array_type or double Return the average along the specified axis. When returned is True, return a tuple with the average as the first element and the sum of the weights as the second element. sum_of_weights is of the same type as retval. The result dtype follows a genereal pattern. If weights is None, the result dtype will be that of a , or float64 if a is integral. Otherwise, if weights is not None and a is non- integral, the result type will be the type of lowest precision capable of representing values of both a and weights. If a happens to be integral, the previous rules still applies but the result dtype will at least be float64. Raises ZeroDivisionError When all weights along axis are zero. See numpy.ma.average for a version robust to this type of error. TypeError When the length of 1D weights is not the same as the shape of a along axis. See also mean ma.average average for masked arrays – useful if your data contains “missing” values numpy.result_type Returns the type that results from applying the numpy type promotion rules to the arguments. Examples >>> data = np.arange(1, 5) >>> data array([1, 2, 3, 4]) >>> np.average(data) 2.5 >>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1)) 4.0 >>> data = np.arange(6).reshape((3,2)) >>> data array([[0, 1], [2, 3], [4, 5]]) >>> np.average(data, axis=1, weights=[1./4, 3./4]) array([0.75, 2.75, 4.75]) >>> np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last): ... TypeError: Axis must be specified when shapes of a and weights differ. >>> a = np.ones(5, dtype=np.float128) >>> w = np.ones(5, dtype=np.complex64) >>> avg = np.average(a, weights=w) >>> print(avg.dtype) complex256
numpy.reference.generated.numpy.average
numpy.AxisError exception numpy.AxisError(axis, ndim=None, msg_prefix=None)[source] Axis supplied was invalid. This is raised whenever an axis parameter is specified that is larger than the number of array dimensions. For compatibility with code written against older numpy versions, which raised a mixture of ValueError and IndexError for this situation, this exception subclasses both to ensure that except ValueError and except IndexError statements continue to catch AxisError. New in version 1.13. Parameters axisint or str The out of bounds axis or a custom exception message. If an axis is provided, then ndim should be specified as well. ndimint, optional The number of array dimensions. msg_prefixstr, optional A prefix for the exception message. Examples >>> array_1d = np.arange(10) >>> np.cumsum(array_1d, axis=1) Traceback (most recent call last): ... numpy.AxisError: axis 1 is out of bounds for array of dimension 1 Negative axes are preserved: >>> np.cumsum(array_1d, axis=-2) Traceback (most recent call last): ... numpy.AxisError: axis -2 is out of bounds for array of dimension 1 The class constructor generally takes the axis and arrays’ dimensionality as arguments: >>> print(np.AxisError(2, 1, msg_prefix='error')) error: axis 2 is out of bounds for array of dimension 1 Alternatively, a custom exception message can be passed: >>> print(np.AxisError('Custom error message')) Custom error message Attributes axisint, optional The out of bounds axis or None if a custom exception message was provided. This should be the axis as passed by the user, before any normalization to resolve negative indices. New in version 1.22. ndimint, optional The number of array dimensions or None if a custom exception message was provided. New in version 1.22.
numpy.reference.generated.numpy.axiserror
numpy.bartlett numpy.bartlett(M)[source] Return the Bartlett window. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain. Parameters Mint Number of points in the output window. If zero or less, an empty array is returned. Returns outarray The triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero. See also blackman, hamming, hanning, kaiser Notes The Bartlett window is defined as \[w(n) = \frac{2}{M-1} \left( \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right| \right)\] Most references to the Bartlett window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. Note that convolution with this window produces linear interpolation. It is also known as an apodization (which means”removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. The fourier transform of the Bartlett is the product of two sinc functions. Note the excellent discussion in Kanasewich. References 1 M.S. Bartlett, “Periodogram Analysis and Continuous Spectra”, Biometrika 37, 1-16, 1950. 2 E.R. Kanasewich, “Time Sequence Analysis in Geophysics”, The University of Alberta Press, 1975, pp. 109-110. 3 A.V. Oppenheim and R.W. Schafer, “Discrete-Time Signal Processing”, Prentice-Hall, 1999, pp. 468-471. 4 Wikipedia, “Window function”, https://en.wikipedia.org/wiki/Window_function 5 W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, “Numerical Recipes”, Cambridge University Press, 1986, page 429. Examples >>> import matplotlib.pyplot as plt >>> np.bartlett(12) array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273, # may vary 0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636, 0.18181818, 0. ]) Plot the window and its frequency response (requires SciPy and matplotlib): >>> from numpy.fft import fft, fftshift >>> window = np.bartlett(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Bartlett window") Text(0.5, 1.0, 'Bartlett window') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample") Text(0.5, 0, 'Sample') >>> plt.show() >>> plt.figure() <Figure size 640x480 with 0 Axes> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> with np.errstate(divide='ignore', invalid='ignore'): ... response = 20 * np.log10(mag) ... >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Bartlett window") Text(0.5, 1.0, 'Frequency response of Bartlett window') >>> plt.ylabel("Magnitude [dB]") Text(0, 0.5, 'Magnitude [dB]') >>> plt.xlabel("Normalized frequency [cycles per sample]") Text(0.5, 0, 'Normalized frequency [cycles per sample]') >>> _ = plt.axis('tight') >>> plt.show()
numpy.reference.generated.numpy.bartlett