doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.distutils.misc_util.get_ext_source_files(ext)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_ext_source_files
numpy.distutils.misc_util.get_frame(level=0)[source] Return frame object from call stack with given level.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_frame
numpy.distutils.misc_util.get_info(pkgname, dirs=None)[source] Return an info dict for a given C library. The info dict contains the necessary options to use the C library. Parameters pkgnamestr Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirssequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns infodict The dictionary with build information. Raises PkgNotFound If the package is not found. See also Configuration.add_npy_pkg_config, Configuration.add_installed_library get_pkg_info Examples To get the necessary information for the npymath library from NumPy: >>> npymath_info = np.distutils.misc_util.get_info('npymath') >>> npymath_info {'define_macros': [], 'libraries': ['npymath'], 'library_dirs': ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']} This info dict can then be used as input to a Configuration instance: config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_info
numpy.distutils.misc_util.get_language(sources)[source] Determine language value (c,f77,f90) from sources
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_language
numpy.distutils.misc_util.get_lib_source_files(lib)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_lib_source_files
numpy.distutils.misc_util.get_mathlibs(path=None)[source] Return the MATHLIB line from numpyconfig.h
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_mathlibs
numpy.distutils.misc_util.get_num_build_jobs()[source] Get number of parallel build jobs set by the –parallel command line argument of setup.py If the command did not receive a setting the environment variable NPY_NUM_BUILD_JOBS is checked. If that is unset, return the number of processors on the system, with a maximum of 8 (to prevent overloading the system if there a lot of CPUs). Returns outint number of parallel jobs that can be run
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_num_build_jobs
numpy.distutils.misc_util.get_numpy_include_dirs()[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_numpy_include_dirs
numpy.distutils.misc_util.get_pkg_info(pkgname, dirs=None)[source] Return library info for the given package. Parameters pkgnamestr Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirssequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns pkginfoclass instance The LibraryInfo instance containing the build information. Raises PkgNotFound If the package is not found. See also Configuration.add_npy_pkg_config, Configuration.add_installed_library get_info
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_pkg_info
numpy.distutils.misc_util.get_script_files(scripts)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_script_files
numpy.distutils.misc_util.gpaths(paths, local_path='', include_non_existing=True)[source] Apply glob to paths and prepend local_path if needed.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.gpaths
numpy.distutils.misc_util.green_text(s)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.green_text
numpy.distutils.misc_util.has_cxx_sources(sources)[source] Return True if sources contains C++ files
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.has_cxx_sources
numpy.distutils.misc_util.has_f_sources(sources)[source] Return True if sources contains Fortran files
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.has_f_sources
numpy.distutils.misc_util.is_local_src_dir(directory)[source] Return true if directory is local directory.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.is_local_src_dir
numpy.distutils.misc_util.is_sequence(seq)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.is_sequence
numpy.distutils.misc_util.is_string(s)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.is_string
numpy.distutils.misc_util.mingw32()[source] Return true when using mingw32 environment.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.mingw32
numpy.distutils.misc_util.minrelpath(path)[source] Resolve and ‘.’ from path.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.minrelpath
numpy.distutils.misc_util.njoin(*path)[source] Join two or more pathname components + - convert a /-separated pathname to one using the OS’s path separator. - resolve and from path. Either passing n arguments as in njoin(‘a’,’b’), or a sequence of n names as in njoin([‘a’,’b’]) is handled, or a mixture of such arguments.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.njoin
numpy.distutils.misc_util.red_text(s)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.red_text
numpy.distutils.misc_util.sanitize_cxx_flags(cxxflags)[source] Some flags are valid for C but not C++. Prune them.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.sanitize_cxx_flags
numpy.distutils.misc_util.terminal_has_colors()[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.terminal_has_colors
numpy.distutils.misc_util.yellow_text(s)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.yellow_text
numpy.divide numpy.divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'true_divide'> Returns a true division of the inputs, element-wise. Unlike ‘floor division’, true division adjusts the output type to present the best answer, regardless of input types. Parameters x1array_like Dividend array. x2array_like Divisor array. 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 outndarray or scalar This is a scalar if both x1 and x2 are scalars. Notes In Python, // is the floor division operator and / the true division operator. The true_divide(x1, x2) function is equivalent to true division in Python. Examples >>> x = np.arange(5) >>> np.true_divide(x, 4) array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x/4 array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4 array([0, 0, 0, 0, 1]) The / operator can be used as a shorthand for np.true_divide on ndarrays. >>> x = np.arange(5) >>> x / 4 array([0. , 0.25, 0.5 , 0.75, 1. ])
numpy.reference.generated.numpy.divide
numpy.divmod numpy.divmod(x1, x2, [out1, out2, ]/, [out=(None, None), ]*, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'divmod'> Return element-wise quotient and remainder simultaneously. New in version 1.13.0. np.divmod(x, y) is equivalent to (x // y, x % y), but faster because it avoids redundant work. It is used to implement the Python built-in function divmod on NumPy arrays. Parameters x1array_like Dividend array. x2array_like Divisor array. 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 out1ndarray Element-wise quotient resulting from floor division. This is a scalar if both x1 and x2 are scalars. out2ndarray Element-wise remainder from floor division. This is a scalar if both x1 and x2 are scalars. See also floor_divide Equivalent to Python’s // operator. remainder Equivalent to Python’s % operator. modf Equivalent to divmod(x, 1) for positive x with the return values switched. Examples >>> np.divmod(np.arange(5), 3) (array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1])) The divmod function can be used as a shorthand for np.divmod on ndarrays. >>> x = np.arange(5) >>> divmod(x, 3) (array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))
numpy.reference.generated.numpy.divmod
numpy.dot numpy.dot(a, b, out=None) Dot product of two arrays. Specifically, If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred. If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b. If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) Parameters aarray_like First argument. barray_like Second argument. outndarray, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. Returns outputndarray Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned. Raises ValueError If the last dimension of a is not the same size as the second-to-last dimension of b. See also vdot Complex-conjugating dot product. tensordot Sum products over arbitrary axes. einsum Einstein summation convention. matmul ‘@’ operator as method with out parameter. linalg.multi_dot Chained dot product. Examples >>> np.dot(3, 4) 12 Neither argument is complex-conjugated: >>> np.dot([2j, 3j], [2j, 3j]) (-13+0j) For 2-D arrays it is the matrix product: >>> a = [[1, 0], [0, 1]] >>> b = [[4, 1], [2, 2]] >>> np.dot(a, b) array([[4, 1], [2, 2]]) >>> a = np.arange(3*4*5*6).reshape((3,4,5,6)) >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3)) >>> np.dot(a, b)[2,3,2,1,2,2] 499128 >>> sum(a[2,3,2,:] * b[1,2,:,2]) 499128
numpy.reference.generated.numpy.dot
class numpy.double(x=0, /)[source] Double-precision floating-point number type, compatible with Python float and C double. Character code 'd' Alias numpy.float_ Alias on this platform (Linux x86_64) numpy.float64: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.
numpy.reference.arrays.scalars#numpy.double
numpy.dsplit numpy.dsplit(ary, indices_or_sections)[source] Split array into multiple sub-arrays along the 3rd axis (depth). Please refer to the split documentation. dsplit is equivalent to split with axis=2, the array is always split along the third axis provided the array dimension is greater than or equal to 3. See also split Split an array into multiple sub-arrays of equal size. Examples >>> x = np.arange(16.0).reshape(2, 2, 4) >>> x array([[[ 0., 1., 2., 3.], [ 4., 5., 6., 7.]], [[ 8., 9., 10., 11.], [12., 13., 14., 15.]]]) >>> np.dsplit(x, 2) [array([[[ 0., 1.], [ 4., 5.]], [[ 8., 9.], [12., 13.]]]), array([[[ 2., 3.], [ 6., 7.]], [[10., 11.], [14., 15.]]])] >>> np.dsplit(x, np.array([3, 6])) [array([[[ 0., 1., 2.], [ 4., 5., 6.]], [[ 8., 9., 10.], [12., 13., 14.]]]), array([[[ 3.], [ 7.]], [[11.], [15.]]]), array([], shape=(2, 2, 0), dtype=float64)]
numpy.reference.generated.numpy.dsplit
numpy.dstack numpy.dstack(tup)[source] Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1). Rebuilds arrays divided by dsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. Parameters tupsequence of arrays The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape. Returns stackedndarray The array formed by stacking the given arrays, will be at least 3-D. See also concatenate Join a sequence of arrays along an existing axis. stack Join a sequence of arrays along a new axis. block Assemble an nd-array from nested lists of blocks. vstack Stack arrays in sequence vertically (row wise). hstack Stack arrays in sequence horizontally (column wise). column_stack Stack 1-D arrays as columns into a 2-D array. dsplit Split array along third axis. Examples >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.dstack((a,b)) array([[[1, 2], [2, 3], [3, 4]]]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.dstack((a,b)) array([[[1, 2]], [[2, 3]], [[3, 4]]])
numpy.reference.generated.numpy.dstack
numpy.dtype class numpy.dtype(dtype, align=False, copy=False)[source] Create a data type object. A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types. Parameters dtype Object to be converted to a data type object. alignbool, optional Add padding to the fields to match what a C compiler would output for a similar C-struct. Can be True only if obj is a dictionary or a comma-separated string. If a struct dtype is being created, this also sets a sticky alignment flag isalignedstruct. copybool, optional Make a new copy of the data-type object. If False, the result may just be a reference to a built-in data-type object. See also result_type Examples Using array-scalar type: >>> np.dtype(np.int16) dtype('int16') Structured type, one field name ‘f1’, containing int16: >>> np.dtype([('f1', np.int16)]) dtype([('f1', '<i2')]) Structured type, one field named ‘f1’, in itself containing a structured type with one field: >>> np.dtype([('f1', [('f1', np.int16)])]) dtype([('f1', [('f1', '<i2')])]) Structured type, two fields: the first field contains an unsigned int, the second an int32: >>> np.dtype([('f1', np.uint64), ('f2', np.int32)]) dtype([('f1', '<u8'), ('f2', '<i4')]) Using array-protocol type strings: >>> np.dtype([('a','f8'),('b','S10')]) dtype([('a', '<f8'), ('b', 'S10')]) Using comma-separated field formats. The shape is (2,3): >>> np.dtype("i4, (2,3)f8") dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))]) Using tuples. int is a fixed type, 3 the field’s shape. void is a flexible type, here of size 10: >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)]) dtype([('hello', '<i8', (3,)), ('world', 'V10')]) Subdivide int16 into 2 int8’s, called x and y. 0 and 1 are the offsets in bytes: >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)})) dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')])) Using dictionaries. Two fields named ‘gender’ and ‘age’: >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]}) dtype([('gender', 'S1'), ('age', 'u1')]) Offsets in bytes, here 0 and 25: >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)}) dtype([('surname', 'S25'), ('age', 'u1')]) Attributes alignment The required alignment (bytes) of this data-type according to the compiler. base Returns dtype for the base element of the subarrays, regardless of their dimension or shape. byteorder A character indicating the byte-order of this data-type object. char A unique character code for each of the 21 different built-in types. descr __array_interface__ description of the data-type. fields Dictionary of named fields defined for this data type, or None. flags Bit-flags describing how this data type is to be interpreted. hasobject Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes. isalignedstruct Boolean indicating whether the dtype is a struct which maintains field alignment. isbuiltin Integer indicating how this dtype relates to the built-in dtypes. isnative Boolean indicating whether the byte order of this dtype is native to the platform. itemsize The element size of this data-type object. kind A character code (one of ‘biufcmMOSUV’) identifying the general kind of data. metadata Either None or a readonly dictionary of metadata (mappingproxy). name A bit-width name for this data-type. names Ordered list of field names, or None if there are no fields. ndim Number of dimensions of the sub-array if this data type describes a sub-array, and 0 otherwise. num A unique number for each of the 21 different built-in types. shape Shape tuple of the sub-array if this data type describes a sub-array, and () otherwise. str The array-protocol typestring of this data-type object. subdtype Tuple (item_dtype, shape) if this dtype describes a sub-array, and None otherwise. type Methods newbyteorder([new_order]) Return a new dtype with a different byte order.
numpy.reference.generated.numpy.dtype
numpy.e Euler’s constant, base of natural logarithms, Napier’s constant. e = 2.71828182845904523536028747135266249775724709369995... See Also exp : Exponential function log : Natural logarithm References https://en.wikipedia.org/wiki/E_%28mathematical_constant%29
numpy.reference.constants#numpy.e
numpy.ediff1d numpy.ediff1d(ary, to_end=None, to_begin=None)[source] The differences between consecutive elements of an array. Parameters aryarray_like If necessary, will be flattened before the differences are taken. to_endarray_like, optional Number(s) to append at the end of the returned differences. to_beginarray_like, optional Number(s) to prepend at the beginning of the returned differences. Returns ediff1dndarray The differences. Loosely, this is ary.flat[1:] - ary.flat[:-1]. See also diff, gradient Notes When applied to masked arrays, this function drops the mask information if the to_begin and/or to_end parameters are used. Examples >>> x = np.array([1, 2, 4, 7, 0]) >>> np.ediff1d(x) array([ 1, 2, 3, -7]) >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99])) array([-99, 1, 2, ..., -7, 88, 99]) The returned array is always 1D. >>> y = [[1, 2, 4], [1, 6, 24]] >>> np.ediff1d(y) array([ 1, 2, -3, 5, 18])
numpy.reference.generated.numpy.ediff1d
numpy.einsum numpy.einsum(subscripts, *operands, out=None, dtype=None, order='K', casting='safe', optimize=False)[source] Evaluates the Einstein summation convention on the operands. Using the Einstein summation convention, many common multi-dimensional, linear algebraic array operations can be represented in a simple fashion. In implicit mode einsum computes these values. In explicit mode, einsum provides further flexibility to compute other array operations that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels. See the notes and examples for clarification. Parameters subscriptsstr Specifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator ‘->’ is included as well as subscript labels of the precise output form. operandslist of array_like These are the arrays for the operation. outndarray, optional If provided, the calculation is done into this array. dtype{data-type, None}, optional If provided, forces the calculation to use the data type specified. Note that you may have to also give a more liberal casting parameter to allow the conversions. Default is None. order{‘C’, ‘F’, ‘A’, ‘K’}, optional Controls the memory layout of the output. ‘C’ means it should be C contiguous. ‘F’ means it should be Fortran contiguous, ‘A’ means it should be ‘F’ if the inputs are all ‘F’, ‘C’ otherwise. ‘K’ means it should be as close to the layout as the inputs as is possible, including arbitrarily permuted axes. Default is ‘K’. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional Controls what kind of data casting may occur. Setting this to ‘unsafe’ is not recommended, as it can adversely affect accumulations. ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done. Default is ‘safe’. optimize{False, True, ‘greedy’, ‘optimal’}, optional Controls if intermediate optimization should occur. No optimization will occur if False and True will default to the ‘greedy’ algorithm. Also accepts an explicit contraction list from the np.einsum_path function. See np.einsum_path for more details. Defaults to False. Returns outputndarray The calculation based on the Einstein summation convention. See also einsum_path, dot, inner, outer, tensordot, linalg.multi_dot einops similar verbose interface is provided by einops package to cover additional operations: transpose, reshape/flatten, repeat/tile, squeeze/unsqueeze and reductions. opt_einsum opt_einsum optimizes contraction order for einsum-like expressions in backend-agnostic manner. Notes New in version 1.6.0. The Einstein summation convention can be used to compute many multi-dimensional, linear algebraic array operations. einsum provides a succinct way of representing these. A non-exhaustive list of these operations, which can be computed by einsum, is shown below along with examples: Trace of an array, numpy.trace. Return a diagonal, numpy.diag. Array axis summations, numpy.sum. Transpositions and permutations, numpy.transpose. Matrix multiplication and dot product, numpy.matmul numpy.dot. Vector inner and outer products, numpy.inner numpy.outer. Broadcasting, element-wise and scalar multiplication, numpy.multiply. Tensor contractions, numpy.tensordot. Chained array operations, in efficient calculation order, numpy.einsum_path. The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Whenever a label is repeated it is summed, so np.einsum('i,i', a, b) is equivalent to np.inner(a,b). If a label appears only once, it is not summed, so np.einsum('i', a) produces a view of a with no changes. A further example np.einsum('ij,jk', a, b) describes traditional matrix multiplication and is equivalent to np.matmul(a,b). Repeated subscript labels in one operand take the diagonal. For example, np.einsum('ii', a) is equivalent to np.trace(a). In implicit mode, the chosen subscripts are important since the axes of the output are reordered alphabetically. This means that np.einsum('ij', a) doesn’t affect a 2D array, while np.einsum('ji', a) takes its transpose. Additionally, np.einsum('ij,jk', a, b) returns a matrix multiplication, while, np.einsum('ij,jh', a, b) returns the transpose of the multiplication since subscript ‘h’ precedes subscript ‘i’. In explicit mode the output can be directly controlled by specifying output subscript labels. This requires the identifier ‘->’ as well as the list of output subscript labels. This feature increases the flexibility of the function since summing can be disabled or forced when required. The call np.einsum('i->', a) is like np.sum(a, axis=-1), and np.einsum('ii->i', a) is like np.diag(a). The difference is that einsum does not allow broadcasting by default. Additionally np.einsum('ij,jh->ih', a, b) directly specifies the order of the output subscript labels and therefore returns matrix multiplication, unlike the example above in implicit mode. To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b). When there is only one operand, no axes are summed, and no output parameter is provided, a view into the operand is returned instead of a new array. Thus, taking the diagonal as np.einsum('ii->i', a) produces a view (changed in version 1.10.0). einsum also provides an alternative way to provide the subscripts and operands as einsum(op0, sublist0, op1, sublist1, ..., [sublistout]). If the output shape is not provided in this format einsum will be calculated in implicit mode, otherwise it will be performed explicitly. The examples below have corresponding einsum calls with the two parameter methods. New in version 1.10.0. Views returned from einsum are now writeable whenever the input array is writeable. For example, np.einsum('ijk...->kji...', a) will now have the same effect as np.swapaxes(a, 0, 2) and np.einsum('ii->i', a) will return a writeable view of the diagonal of a 2D array. New in version 1.12.0. Added the optimize argument which will optimize the contraction order of an einsum expression. For a contraction with three or more operands this can greatly increase the computational efficiency at the cost of a larger memory footprint during computation. Typically a ‘greedy’ algorithm is applied which empirical tests have shown returns the optimal path in the majority of cases. In some cases ‘optimal’ will return the superlative path through a more expensive, exhaustive search. For iterative calculations it may be advisable to calculate the optimal path once and reuse that path by supplying it as an argument. An example is given below. See numpy.einsum_path for more details. Examples >>> a = np.arange(25).reshape(5,5) >>> b = np.arange(5) >>> c = np.arange(6).reshape(2,3) Trace of a matrix: >>> np.einsum('ii', a) 60 >>> np.einsum(a, [0,0]) 60 >>> np.trace(a) 60 Extract the diagonal (requires explicit form): >>> np.einsum('ii->i', a) array([ 0, 6, 12, 18, 24]) >>> np.einsum(a, [0,0], [0]) array([ 0, 6, 12, 18, 24]) >>> np.diag(a) array([ 0, 6, 12, 18, 24]) Sum over an axis (requires explicit form): >>> np.einsum('ij->i', a) array([ 10, 35, 60, 85, 110]) >>> np.einsum(a, [0,1], [0]) array([ 10, 35, 60, 85, 110]) >>> np.sum(a, axis=1) array([ 10, 35, 60, 85, 110]) For higher dimensional arrays summing a single axis can be done with ellipsis: >>> np.einsum('...j->...', a) array([ 10, 35, 60, 85, 110]) >>> np.einsum(a, [Ellipsis,1], [Ellipsis]) array([ 10, 35, 60, 85, 110]) Compute a matrix transpose, or reorder any number of axes: >>> np.einsum('ji', c) array([[0, 3], [1, 4], [2, 5]]) >>> np.einsum('ij->ji', c) array([[0, 3], [1, 4], [2, 5]]) >>> np.einsum(c, [1,0]) array([[0, 3], [1, 4], [2, 5]]) >>> np.transpose(c) array([[0, 3], [1, 4], [2, 5]]) Vector inner products: >>> np.einsum('i,i', b, b) 30 >>> np.einsum(b, [0], b, [0]) 30 >>> np.inner(b,b) 30 Matrix vector multiplication: >>> np.einsum('ij,j', a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum(a, [0,1], b, [1]) array([ 30, 80, 130, 180, 230]) >>> np.dot(a, b) array([ 30, 80, 130, 180, 230]) >>> np.einsum('...j,j', a, b) array([ 30, 80, 130, 180, 230]) Broadcasting and scalar multiplication: >>> np.einsum('..., ...', 3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.einsum(',ij', 3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.einsum(3, [Ellipsis], c, [Ellipsis]) array([[ 0, 3, 6], [ 9, 12, 15]]) >>> np.multiply(3, c) array([[ 0, 3, 6], [ 9, 12, 15]]) Vector outer product: >>> np.einsum('i,j', np.arange(2)+1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.einsum(np.arange(2)+1, [0], b, [1]) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) >>> np.outer(np.arange(2)+1, b) array([[0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]) Tensor contraction: >>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> np.einsum('ijk,jil->kl', a, b) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3]) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) >>> np.tensordot(a,b, axes=([1,0],[0,1])) array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) Writeable returned arrays (since version 1.10.0): >>> a = np.zeros((3, 3)) >>> np.einsum('ii->i', a)[:] = 1 >>> a array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) Example of ellipsis use: >>> a = np.arange(6).reshape((3,2)) >>> b = np.arange(12).reshape((4,3)) >>> np.einsum('ki,jk->ij', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) >>> np.einsum('ki,...k->i...', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) >>> np.einsum('k...,jk', a, b) array([[10, 28, 46, 64], [13, 40, 67, 94]]) Chained array operations. For more complicated contractions, speed ups might be achieved by repeatedly computing a ‘greedy’ path or pre-computing the ‘optimal’ path and repeatedly applying it, using an einsum_path insertion (since version 1.12.0). Performance improvements can be particularly significant with larger arrays: >>> a = np.ones(64).reshape(2,4,8) Basic einsum: ~1520ms (benchmarked on 3.1GHz Intel i5.) >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a) Sub-optimal einsum (due to repeated path calculation time): ~330ms >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal') Greedy einsum (faster optimal path approximation): ~160ms >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy') Optimal einsum (best usage pattern in some use cases): ~110ms >>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal')[0] >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)
numpy.reference.generated.numpy.einsum
numpy.einsum_path numpy.einsum_path(subscripts, *operands, optimize='greedy')[source] Evaluates the lowest cost contraction order for an einsum expression by considering the creation of intermediate arrays. Parameters subscriptsstr Specifies the subscripts for summation. *operandslist of array_like These are the arrays for the operation. optimize{bool, list, tuple, ‘greedy’, ‘optimal’} Choose the type of path. If a tuple is provided, the second argument is assumed to be the maximum intermediate size created. If only a single argument is provided the largest input or output array size is used as a maximum intermediate size. if a list is given that starts with einsum_path, uses this as the contraction path if False no optimization is taken if True defaults to the ‘greedy’ algorithm ‘optimal’ An algorithm that combinatorially explores all possible ways of contracting the listed tensors and choosest the least costly path. Scales exponentially with the number of terms in the contraction. ‘greedy’ An algorithm that chooses the best pair contraction at each step. Effectively, this algorithm searches the largest inner, Hadamard, and then outer products at each step. Scales cubically with the number of terms in the contraction. Equivalent to the ‘optimal’ path for most contractions. Default is ‘greedy’. Returns pathlist of tuples A list representation of the einsum path. string_reprstr A printable representation of the einsum path. See also einsum, linalg.multi_dot Notes The resulting path indicates which terms of the input contraction should be contracted first, the result of this contraction is then appended to the end of the contraction list. This list can then be iterated over until all intermediate contractions are complete. Examples We can begin with a chain dot example. In this case, it is optimal to contract the b and c tensors first as represented by the first element of the path (1, 2). The resulting tensor is added to the end of the contraction and the remaining contraction (0, 1) is then completed. >>> np.random.seed(123) >>> a = np.random.rand(2, 2) >>> b = np.random.rand(2, 5) >>> c = np.random.rand(5, 2) >>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy') >>> print(path_info[0]) ['einsum_path', (1, 2), (0, 1)] >>> print(path_info[1]) Complete contraction: ij,jk,kl->il # may vary Naive scaling: 4 Optimized scaling: 3 Naive FLOP count: 1.600e+02 Optimized FLOP count: 5.600e+01 Theoretical speedup: 2.857 Largest intermediate: 4.000e+00 elements ------------------------------------------------------------------------- scaling current remaining ------------------------------------------------------------------------- 3 kl,jk->jl ij,jl->il 3 jl,ij->il il->il A more complex index transformation example. >>> I = np.random.rand(10, 10, 10, 10) >>> C = np.random.rand(10, 10) >>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C, ... optimize='greedy') >>> print(path_info[0]) ['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)] >>> print(path_info[1]) Complete contraction: ea,fb,abcd,gc,hd->efgh # may vary Naive scaling: 8 Optimized scaling: 5 Naive FLOP count: 8.000e+08 Optimized FLOP count: 8.000e+05 Theoretical speedup: 1000.000 Largest intermediate: 1.000e+04 elements -------------------------------------------------------------------------- scaling current remaining -------------------------------------------------------------------------- 5 abcd,ea->bcde fb,gc,hd,bcde->efgh 5 bcde,fb->cdef gc,hd,cdef->efgh 5 cdef,gc->defg hd,defg->efgh 5 defg,hd->efgh efgh->efgh
numpy.reference.generated.numpy.einsum_path
numpy.empty numpy.empty(shape, dtype=float, order='C', *, like=None) Return a new array of given shape and type, without initializing entries. Parameters shapeint or tuple of int Shape of the empty array, e.g., (2, 3) or 2. dtypedata-type, optional Desired output data-type for the array, e.g, numpy.int8. Default is numpy.float64. order{‘C’, ‘F’}, optional, default: ‘C’ Whether to store multi-dimensional data in row-major (C-style) or column-major (Fortran-style) order in memory. 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 of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None. See also empty_like Return an empty array with shape and type of input. 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 empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution. Examples >>> np.empty([2, 2]) array([[ -9.74499359e+001, 6.69583040e-309], [ 2.13182611e-314, 3.06959433e-309]]) #uninitialized >>> np.empty([2, 2], dtype=int) array([[-1073741821, -1067949133], [ 496041986, 19249760]]) #uninitialized
numpy.reference.generated.numpy.empty
numpy.empty_like numpy.empty_like(prototype, dtype=None, order='K', subok=True, shape=None) Return a new array with the same shape and type as a given array. Parameters prototypearray_like The shape and data-type of prototype define these same attributes of the returned array. dtypedata-type, optional Overrides the data type of the result. New in version 1.6.0. order{‘C’, ‘F’, ‘A’, or ‘K’}, optional Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if prototype is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of prototype as closely as possible. New in version 1.6.0. subokbool, optional. If True, then the newly created array will use the sub-class type of prototype, otherwise it will be a base-class array. Defaults to True. shapeint or sequence of ints, optional. Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied. New in version 1.17.0. Returns outndarray Array of uninitialized (arbitrary) data with the same shape and type as prototype. See also 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. Notes This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be marginally faster than the functions that do set the array values. Examples >>> a = ([1,2,3], [4,5,6]) # a is array-like >>> np.empty_like(a) array([[-1073741821, -1073741821, 3], # uninitialized [ 0, 0, -1073741821]]) >>> a = np.array([[1., 2., 3.],[4.,5.,6.]]) >>> np.empty_like(a) array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]])
numpy.reference.generated.numpy.empty_like
numpy.equal numpy.equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'equal'> Return (x1 == x2) element-wise. Parameters x1, x2array_like Input arrays. 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 outndarray or scalar Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. See also not_equal, greater_equal, less_equal, greater, less Examples >>> np.equal([0, 1, 3], np.arange(3)) array([ True, True, False]) What is compared are values, not types. So an int (1) and an array of length one can evaluate as True: >>> np.equal(1, np.ones(1)) array([ True]) The == operator can be used as a shorthand for np.equal on ndarrays. >>> a = np.array([2, 4, 6]) >>> b = np.array([2, 4, 2]) >>> a == b array([ True, True, False])
numpy.reference.generated.numpy.equal
numpy.errstate class numpy.errstate(**kwargs)[source] Context manager for floating-point error handling. Using an instance of errstate as a context manager allows statements in that context to execute with a known error handling behavior. Upon entering the context the error handling is set with seterr and seterrcall, and upon exiting it is reset to what it was before. Changed in version 1.17.0: errstate is also usable as a function decorator, saving a level of indentation if an entire function is wrapped. See contextlib.ContextDecorator for more information. Parameters kwargs{divide, over, under, invalid} Keyword arguments. The valid keywords are the possible floating-point exceptions. Each keyword should have a string value that defines the treatment for the particular error. Possible values are {‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}. See also seterr, geterr, seterrcall, geterrcall Notes For complete documentation of the types of floating-point exceptions and treatment options, see seterr. Examples >>> olderr = np.seterr(all='ignore') # Set error handling to known state. >>> np.arange(3) / 0. array([nan, inf, inf]) >>> with np.errstate(divide='warn'): ... np.arange(3) / 0. array([nan, inf, inf]) >>> np.sqrt(-1) nan >>> with np.errstate(invalid='raise'): ... np.sqrt(-1) Traceback (most recent call last): File "<stdin>", line 2, in <module> FloatingPointError: invalid value encountered in sqrt Outside the context the error handling behavior has not changed: >>> np.geterr() {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'} Methods __call__(func) Call self as a function.
numpy.reference.generated.numpy.errstate
numpy.euler_gamma γ = 0.5772156649015328606065120900824024310421... References https://en.wikipedia.org/wiki/Euler-Mascheroni_constant
numpy.reference.constants#numpy.euler_gamma
numpy.exp numpy.exp(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'exp'> Calculate the exponential of all elements in the input array. Parameters xarray_like Input values. 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 Output array, element-wise exponential of x. This is a scalar if x is a scalar. See also expm1 Calculate exp(x) - 1 for all elements in the array. exp2 Calculate 2**x for all elements in the array. Notes The irrational number e is also known as Euler’s number. It is approximately 2.718281, and is the base of the natural logarithm, ln (this means that, if \(x = \ln y = \log_e y\), then \(e^x = y\). For real input, exp(x) is always positive. For complex arguments, x = a + ib, we can write \(e^x = e^a e^{ib}\). The first term, \(e^a\), is already known (it is the real argument, described above). The second term, \(e^{ib}\), is \(\cos b + i \sin b\), a function with magnitude 1 and a periodic phase. References 1 Wikipedia, “Exponential function”, https://en.wikipedia.org/wiki/Exponential_function 2 M. Abramovitz and I. A. Stegun, “Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables,” Dover, 1964, p. 69, https://personal.math.ubc.ca/~cbm/aands/page_69.htm Examples Plot the magnitude and phase of exp(x) in the complex plane: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-2*np.pi, 2*np.pi, 100) >>> xx = x + 1j * x[:, np.newaxis] # a + ib over complex plane >>> out = np.exp(xx) >>> plt.subplot(121) >>> plt.imshow(np.abs(out), ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='gray') >>> plt.title('Magnitude of exp(x)') >>> plt.subplot(122) >>> plt.imshow(np.angle(out), ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='hsv') >>> plt.title('Phase (angle) of exp(x)') >>> plt.show()
numpy.reference.generated.numpy.exp
numpy.exp2 numpy.exp2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'exp2'> Calculate 2**p for all p in the input array. Parameters xarray_like Input values. 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 Element-wise 2 to the power x. This is a scalar if x is a scalar. See also power Notes New in version 1.3.0. Examples >>> np.exp2([2, 3]) array([ 4., 8.])
numpy.reference.generated.numpy.exp2
numpy.expand_dims numpy.expand_dims(a, axis)[source] Expand the shape of an array. Insert a new axis that will appear at the axis position in the expanded array shape. Parameters aarray_like Input array. axisint or tuple of ints Position in the expanded axes where the new axis (or axes) is placed. Deprecated since version 1.13.0: Passing an axis where axis > a.ndim will be treated as axis == a.ndim, and passing axis < -a.ndim - 1 will be treated as axis == 0. This behavior is deprecated. Changed in version 1.18.0: A tuple of axes is now supported. Out of range axes as described above are now forbidden and raise an AxisError. Returns resultndarray View of a with the number of dimensions increased. See also squeeze The inverse operation, removing singleton dimensions reshape Insert, remove, and combine dimensions, and resize existing ones doc.indexing, atleast_1d, atleast_2d, atleast_3d Examples >>> x = np.array([1, 2]) >>> x.shape (2,) The following is equivalent to x[np.newaxis, :] or x[np.newaxis]: >>> y = np.expand_dims(x, axis=0) >>> y array([[1, 2]]) >>> y.shape (1, 2) The following is equivalent to x[:, np.newaxis]: >>> y = np.expand_dims(x, axis=1) >>> y array([[1], [2]]) >>> y.shape (2, 1) axis may also be a tuple: >>> y = np.expand_dims(x, axis=(0, 1)) >>> y array([[[1, 2]]]) >>> y = np.expand_dims(x, axis=(2, 0)) >>> y array([[[1], [2]]]) Note that some examples may use None instead of np.newaxis. These are the same objects: >>> np.newaxis is None True
numpy.reference.generated.numpy.expand_dims
numpy.expm1 numpy.expm1(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'expm1'> Calculate exp(x) - 1 for all elements in the array. Parameters xarray_like Input values. 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 Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar. See also log1p log(1 + x), the inverse of expm1. Notes This function provides greater precision than exp(x) - 1 for small values of x. Examples The true value of exp(1e-10) - 1 is 1.00000000005e-10 to about 32 significant digits. This example shows the superiority of expm1 in this case. >>> np.expm1(1e-10) 1.00000000005e-10 >>> np.exp(1e-10) - 1 1.000000082740371e-10
numpy.reference.generated.numpy.expm1
numpy.extract numpy.extract(condition, arr)[source] Return the elements of an array that satisfy some condition. This is equivalent to np.compress(ravel(condition), ravel(arr)). If condition is boolean np.extract is equivalent to arr[condition]. Note that place does the exact opposite of extract. Parameters conditionarray_like An array whose nonzero or True entries indicate the elements of arr to extract. arrarray_like Input array of the same size as condition. Returns extractndarray Rank 1 array of values from arr where condition is True. See also take, put, copyto, compress, place Examples >>> arr = np.arange(12).reshape((3, 4)) >>> arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> condition = np.mod(arr, 3)==0 >>> condition array([[ True, False, False, True], [False, False, True, False], [False, True, False, False]]) >>> np.extract(condition, arr) array([0, 3, 6, 9]) If condition is boolean: >>> arr[condition] array([0, 3, 6, 9])
numpy.reference.generated.numpy.extract
numpy.eye numpy.eye(N, M=None, k=0, dtype=<class 'float'>, order='C', *, like=None)[source] Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters Nint Number of rows in the output. Mint, optional Number of columns in the output. If None, defaults to N. kint, optional Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtypedata-type, optional Data-type of the returned array. order{‘C’, ‘F’}, optional Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory. New in version 1.14.0. 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 Indarray of shape (N,M) An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one. See also identity (almost) equivalent function diag diagonal 2-D array from a 1-D array specified by the user. Examples >>> np.eye(2, dtype=int) array([[1, 0], [0, 1]]) >>> np.eye(3, k=1) array([[0., 1., 0.], [0., 0., 1.], [0., 0., 0.]])
numpy.reference.generated.numpy.eye
numpy.f2py.get_include()[source] Return the directory that contains the fortranobject.c and .h files. Note This function is not needed when building an extension with numpy.distutils directly from .f and/or .pyf files in one go. Python extension modules built with f2py-generated code need to use fortranobject.c as a source file, and include the fortranobject.h header. This function can be used to obtain the directory containing both of these files. Returns include_pathstr Absolute path to the directory containing fortranobject.c and fortranobject.h. See also numpy.get_include function that returns the numpy include directory Notes New in version 1.22.0. Unless the build system you are using has specific support for f2py, building a Python extension using a .pyf signature file is a two-step process. For a module mymod: Step 1: run python -m numpy.f2py mymod.pyf --quiet. This generates _mymodmodule.c and (if needed) _fblas-f2pywrappers.f files next to mymod.pyf. Step 2: build your Python extension module. This requires the following source files: _mymodmodule.c _mymod-f2pywrappers.f (if it was generated in step 1) fortranobject.c
numpy.f2py.usage#numpy.f2py.get_include
numpy.f2py.run_main(comline_list)[source] Equivalent to running: f2py <args> where <args>=string.join(<list>,' '), but in Python. Unless -h is used, this function returns a dictionary containing information on generated modules and their dependencies on source files. For example, the command f2py -m scalar scalar.f can be executed from Python as follows You cannot build extension modules with this function, that is, using -c is not allowed. Use compile command instead Examples >>> import numpy.f2py >>> r = numpy.f2py.run_main(['-m','scalar','doc/source/f2py/scalar.f']) Reading fortran codes... Reading file 'doc/source/f2py/scalar.f' (format:fix,strict) Post-processing... Block: scalar Block: FOO Building modules... Building module "scalar"... Wrote C/API module "scalar" to file "./scalarmodule.c" >>> print(r) {'scalar': {'h': ['/home/users/pearu/src_cvs/f2py/src/fortranobject.h'], 'csrc': ['./scalarmodule.c', '/home/users/pearu/src_cvs/f2py/src/fortranobject.c']}}
numpy.f2py.usage#numpy.f2py.run_main
numpy.fabs numpy.fabs(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'fabs'> Compute the absolute values element-wise. This function returns the absolute values (positive magnitude) of the data in x. Complex values are not handled, use absolute to find the absolute values of complex data. Parameters xarray_like The array of numbers for which the absolute values are required. If x is a scalar, the result y will also be a scalar. 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 yndarray or scalar The absolute values of x, the returned values are always floats. This is a scalar if x is a scalar. See also absolute Absolute values including complex types. Examples >>> np.fabs(-1) 1.0 >>> np.fabs([-1.2, 1.2]) array([ 1.2, 1.2])
numpy.reference.generated.numpy.fabs
numpy.fill_diagonal numpy.fill_diagonal(a, val, wrap=False)[source] Fill the main diagonal of the given array of any dimensionality. For an array a with a.ndim >= 2, the diagonal is the list of locations with indices a[i, ..., i] all identical. This function modifies the input array in-place, it does not return a value. Parameters aarray, at least 2-D. Array whose diagonal is to be filled, it gets modified in-place. valscalar or array_like Value(s) to write on the diagonal. If val is scalar, the value is written along the diagonal. If array-like, the flattened val is written along the diagonal, repeating if necessary to fill all diagonal entries. wrapbool For tall matrices in NumPy version up to 1.6.2, the diagonal “wrapped” after N columns. You can have this behavior with this option. This affects only tall matrices. See also diag_indices, diag_indices_from Notes New in version 1.4.0. This functionality can be obtained via diag_indices, but internally this version uses a much faster implementation that never constructs the indices and uses simple slicing. Examples >>> a = np.zeros((3, 3), int) >>> np.fill_diagonal(a, 5) >>> a array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) The same function can operate on a 4-D array: >>> a = np.zeros((3, 3, 3, 3), int) >>> np.fill_diagonal(a, 4) We only show a few blocks for clarity: >>> a[0, 0] array([[4, 0, 0], [0, 0, 0], [0, 0, 0]]) >>> a[1, 1] array([[0, 0, 0], [0, 4, 0], [0, 0, 0]]) >>> a[2, 2] array([[0, 0, 0], [0, 0, 0], [0, 0, 4]]) The wrap option affects only tall matrices: >>> # tall matrices no wrap >>> a = np.zeros((5, 3), int) >>> np.fill_diagonal(a, 4) >>> a array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [0, 0, 0]]) >>> # tall matrices wrap >>> a = np.zeros((5, 3), int) >>> np.fill_diagonal(a, 4, wrap=True) >>> a array([[4, 0, 0], [0, 4, 0], [0, 0, 4], [0, 0, 0], [4, 0, 0]]) >>> # wide matrices >>> a = np.zeros((3, 5), int) >>> np.fill_diagonal(a, 4, wrap=True) >>> a array([[4, 0, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 4, 0, 0]]) The anti-diagonal can be filled by reversing the order of elements using either numpy.flipud or numpy.fliplr. >>> a = np.zeros((3, 3), int); >>> np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip >>> a array([[0, 0, 1], [0, 2, 0], [3, 0, 0]]) >>> np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip >>> a array([[0, 0, 3], [0, 2, 0], [1, 0, 0]]) Note that the order in which the diagonal is filled varies depending on the flip function.
numpy.reference.generated.numpy.fill_diagonal
numpy.find_common_type numpy.find_common_type(array_types, scalar_types)[source] Determine common type following standard coercion rules. Parameters array_typessequence A list of dtypes or dtype convertible objects representing arrays. scalar_typessequence A list of dtypes or dtype convertible objects representing scalars. Returns datatypedtype The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned. See also dtype, common_type, can_cast, mintypecode Examples >>> np.find_common_type([], [np.int64, np.float32, complex]) dtype('complex128') >>> np.find_common_type([np.int64, np.float32], []) dtype('float64') The standard casting rules ensure that a scalar cannot up-cast an array unless the scalar is of a fundamentally different kind of data (i.e. under a different hierarchy in the data type hierarchy) then the array: >>> np.find_common_type([np.float32], [np.int64, np.float64]) dtype('float32') Complex is of a different type, so it up-casts the float in the array_types argument: >>> np.find_common_type([np.float32], [complex]) dtype('complex128') Type specifier strings are convertible to dtypes and can therefore be used instead of dtypes: >>> np.find_common_type(['f4', 'f4', 'i4'], ['c8']) dtype('complex128')
numpy.reference.generated.numpy.find_common_type
numpy.finfo class numpy.finfo(dtype)[source] Machine limits for floating point types. Parameters dtypefloat, dtype, or instance Kind of floating point data-type about which to get information. See also MachAr The implementation of the tests that produce this information. iinfo The equivalent for integer data types. spacing The distance between a value and the nearest adjacent number nextafter The next floating point value after x1 towards x2 Notes For developers of NumPy: do not instantiate this at the module level. The initial calculation of these parameters is expensive and negatively impacts import times. These objects are cached, so calling finfo() repeatedly inside your functions is not a problem. Note that smallest_normal is not actually the smallest positive representable value in a NumPy floating point type. As in the IEEE-754 standard [1], NumPy floating point types make use of subnormal numbers to fill the gap between 0 and smallest_normal. However, subnormal numbers may have significantly reduced precision [2]. References 1 IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008, pp.1-70, 2008, http://www.doi.org/10.1109/IEEESTD.2008.4610935 2 Wikipedia, “Denormal Numbers”, https://en.wikipedia.org/wiki/Denormal_number Attributes bitsint The number of bits occupied by the type. epsfloat The difference between 1.0 and the next smallest representable float larger than 1.0. For example, for 64-bit binary floats in the IEEE-754 standard, eps = 2**-52, approximately 2.22e-16. epsnegfloat The difference between 1.0 and the next smallest representable float less than 1.0. For example, for 64-bit binary floats in the IEEE-754 standard, epsneg = 2**-53, approximately 1.11e-16. iexpint The number of bits in the exponent portion of the floating point representation. macharMachAr The object which calculated these parameters and holds more detailed information. machepint The exponent that yields eps. maxfloating point number of the appropriate type The largest representable number. maxexpint The smallest positive power of the base (2) that causes overflow. minfloating point number of the appropriate type The smallest representable number, typically -max. minexpint The most negative power of the base (2) consistent with there being no leading 0’s in the mantissa. negepint The exponent that yields epsneg. nexpint The number of bits in the exponent including its sign and bias. nmantint The number of bits in the mantissa. precisionint The approximate number of decimal digits to which this kind of float is precise. resolutionfloating point number of the appropriate type The approximate decimal resolution of this type, i.e., 10**-precision. tinyfloat Return the value for tiny, alias of smallest_normal. smallest_normalfloat Return the value for the smallest normal. smallest_subnormalfloat The smallest positive floating point number with 0 as leading bit in the mantissa following IEEE-754.
numpy.reference.generated.numpy.finfo
numpy.fix numpy.fix(x, out=None)[source] Round to nearest integer towards zero. Round an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats. Parameters xarray_like An array of floats to be rounded outndarray, optional A location into which the result is stored. If provided, it must have a shape that the input broadcasts to. If not provided or None, a freshly-allocated array is returned. Returns outndarray of floats A float array with the same dimensions as the input. If second argument is not supplied then a float array is returned with the rounded values. If a second argument is supplied the result is stored there. The return value out is then a reference to that array. See also rint, trunc, floor, ceil around Round to given number of decimals Examples >>> np.fix(3.14) 3.0 >>> np.fix(3) 3.0 >>> np.fix([2.1, 2.9, -2.1, -2.9]) array([ 2., 2., -2., -2.])
numpy.reference.generated.numpy.fix
numpy.flatiter class numpy.flatiter[source] Flat iterator object to iterate over arrays. A flatiter iterator is returned by x.flat for any array x. It allows iterating over the array as if it were a 1-D array, either in a for-loop or by calling its next method. Iteration is done in row-major, C-style order (the last index varying the fastest). The iterator can also be indexed using basic slicing or advanced indexing. See also ndarray.flat Return a flat iterator over an array. ndarray.flatten Returns a flattened copy of an array. Notes A flatiter iterator can not be constructed directly from Python code by calling the flatiter constructor. Examples >>> x = np.arange(6).reshape(2, 3) >>> fl = x.flat >>> type(fl) <class 'numpy.flatiter'> >>> for item in fl: ... print(item) ... 0 1 2 3 4 5 >>> fl[2:4] array([2, 3]) Attributes base A reference to the array that is iterated over. coords An N-dimensional tuple of current coordinates. index Current flat index into the array. Methods copy() Get a copy of the iterator as a 1-D array.
numpy.reference.generated.numpy.flatiter
numpy.flatnonzero numpy.flatnonzero(a)[source] Return indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0]. Parameters aarray_like Input data. Returns resndarray Output array, containing the indices of the elements of a.ravel() that are non-zero. See also nonzero Return the indices of the non-zero elements of the input array. ravel Return a 1-D array containing the elements of the input array. Examples >>> x = np.arange(-2, 3) >>> x array([-2, -1, 0, 1, 2]) >>> np.flatnonzero(x) array([0, 1, 3, 4]) Use the indices of the non-zero elements as an index array to extract these elements: >>> x.ravel()[np.flatnonzero(x)] array([-2, -1, 1, 2])
numpy.reference.generated.numpy.flatnonzero
class numpy.flexible[source] Abstract base class of all scalar types without predefined length. The actual size of these types depends on the specific np.dtype instantiation.
numpy.reference.arrays.scalars#numpy.flexible
numpy.flip numpy.flip(m, axis=None)[source] Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered. New in version 1.12.0. Parameters marray_like Input array. axisNone or int or tuple of ints, optional Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple. Changed in version 1.15.0: None and tuples of axes are supported Returns outarray_like A view of m with the entries of axis reversed. Since a view is returned, this operation is done in constant time. See also flipud Flip an array vertically (axis=0). fliplr Flip an array horizontally (axis=1). Notes flip(m, 0) is equivalent to flipud(m). flip(m, 1) is equivalent to fliplr(m). flip(m, n) corresponds to m[...,::-1,...] with ::-1 at position n. flip(m) corresponds to m[::-1,::-1,...,::-1] with ::-1 at all positions. flip(m, (0, 1)) corresponds to m[::-1,::-1,...] with ::-1 at position 0 and position 1. Examples >>> A = np.arange(8).reshape((2,2,2)) >>> A array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.flip(A, 0) array([[[4, 5], [6, 7]], [[0, 1], [2, 3]]]) >>> np.flip(A, 1) array([[[2, 3], [0, 1]], [[6, 7], [4, 5]]]) >>> np.flip(A) array([[[7, 6], [5, 4]], [[3, 2], [1, 0]]]) >>> np.flip(A, (0, 2)) array([[[5, 4], [7, 6]], [[1, 0], [3, 2]]]) >>> A = np.random.randn(3,4,5) >>> np.all(np.flip(A,2) == A[:,:,::-1,...]) True
numpy.reference.generated.numpy.flip
numpy.fliplr numpy.fliplr(m)[source] Reverse the order of elements along axis 1 (left/right). For a 2-D array, this flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before. Parameters marray_like Input array, must be at least 2-D. Returns fndarray A view of m with the columns reversed. Since a view is returned, this operation is \(\mathcal O(1)\). See also flipud Flip array in the up/down direction. flip Flip array in one or more dimensions. rot90 Rotate array counterclockwise. Notes Equivalent to m[:,::-1] or np.flip(m, axis=1). Requires the array to be at least 2-D. Examples >>> A = np.diag([1.,2.,3.]) >>> A array([[1., 0., 0.], [0., 2., 0.], [0., 0., 3.]]) >>> np.fliplr(A) array([[0., 0., 1.], [0., 2., 0.], [3., 0., 0.]]) >>> A = np.random.randn(2,3,5) >>> np.all(np.fliplr(A) == A[:,::-1,...]) True
numpy.reference.generated.numpy.fliplr
numpy.flipud numpy.flipud(m)[source] Reverse the order of elements along axis 0 (up/down). For a 2-D array, this flips the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. Parameters marray_like Input array. Returns outarray_like A view of m with the rows reversed. Since a view is returned, this operation is \(\mathcal O(1)\). See also fliplr Flip array in the left/right direction. flip Flip array in one or more dimensions. rot90 Rotate array counterclockwise. Notes Equivalent to m[::-1, ...] or np.flip(m, axis=0). Requires the array to be at least 1-D. Examples >>> A = np.diag([1.0, 2, 3]) >>> A array([[1., 0., 0.], [0., 2., 0.], [0., 0., 3.]]) >>> np.flipud(A) array([[0., 0., 3.], [0., 2., 0.], [1., 0., 0.]]) >>> A = np.random.randn(2,3,5) >>> np.all(np.flipud(A) == A[::-1,...]) True >>> np.flipud([1,2]) array([2, 1])
numpy.reference.generated.numpy.flipud
numpy.float96 numpy.float128[source] Alias for numpy.longdouble, named after its size in bits. The existence of these aliases depends on the platform.
numpy.reference.arrays.scalars#numpy.float128
numpy.float16[source] alias of numpy.half
numpy.reference.arrays.scalars#numpy.float16
numpy.float32[source] alias of numpy.single
numpy.reference.arrays.scalars#numpy.float32
numpy.float64[source] alias of numpy.double
numpy.reference.arrays.scalars#numpy.float64
numpy.float96 numpy.float128[source] Alias for numpy.longdouble, named after its size in bits. The existence of these aliases depends on the platform.
numpy.reference.arrays.scalars#numpy.float96
numpy.float_power numpy.float_power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'float_power'> First array elements raised to powers from second array, element-wise. Raise each base in x1 to the positionally-corresponding power in x2. x1 and x2 must be broadcastable to the same shape. This differs from the power function in that integers, float16, and float32 are promoted to floats with a minimum precision of float64 so that the result is always inexact. The intent is that the function will return a usable result for negative powers and seldom overflow for positive powers. Negative values raised to a non-integral value will return nan. To get complex results, cast the input to complex, or specify the dtype to be complex (see the example below). New in version 1.12.0. Parameters x1array_like The bases. x2array_like The exponents. 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 yndarray The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars. See also power power function that preserves type Examples Cube each element in a list. >>> x1 = range(6) >>> x1 [0, 1, 2, 3, 4, 5] >>> np.float_power(x1, 3) array([ 0., 1., 8., 27., 64., 125.]) Raise the bases to different exponents. >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0] >>> np.float_power(x1, x2) array([ 0., 1., 8., 27., 16., 5.]) The effect of broadcasting. >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> x2 array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> np.float_power(x1, x2) array([[ 0., 1., 8., 27., 16., 5.], [ 0., 1., 8., 27., 16., 5.]]) Negative values raised to a non-integral value will result in nan (and a warning will be generated). >>> x3 = np.array([-1, -4]) >>> with np.errstate(invalid='ignore'): ... p = np.float_power(x3, 1.5) ... >>> p array([nan, nan]) To get complex results, give the argument dtype=complex. >>> np.float_power(x3, 1.5, dtype=complex) array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])
numpy.reference.generated.numpy.float_power
numpy.floor numpy.floor(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'floor'> Return the floor of the input, element-wise. The floor of the scalar x is the largest integer i, such that i <= x. It is often denoted as \(\lfloor x \rfloor\). Parameters xarray_like Input data. 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 yndarray or scalar The floor of each element in x. This is a scalar if x is a scalar. See also ceil, trunc, rint, fix Notes Some spreadsheet programs calculate the “floor-towards-zero”, where floor(-2.5) == -2. NumPy instead uses the definition of floor where floor(-2.5) == -3. The “floor-towards-zero” function is called fix in NumPy. Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.floor(a) array([-2., -2., -1., 0., 1., 1., 2.])
numpy.reference.generated.numpy.floor
numpy.floor_divide numpy.floor_divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'floor_divide'> Return the largest integer smaller or equal to the division of the inputs. It is equivalent to the Python // operator and pairs with the Python % (remainder), function so that a = a % b + b * (a // b) up to roundoff. Parameters x1array_like Numerator. x2array_like Denominator. 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 yndarray y = floor(x1/x2) This is a scalar if both x1 and x2 are scalars. See also remainder Remainder complementary to floor_divide. divmod Simultaneous floor division and remainder. divide Standard division. floor Round a number to the nearest integer toward minus infinity. ceil Round a number to the nearest integer toward infinity. Examples >>> np.floor_divide(7,3) 2 >>> np.floor_divide([1., 2., 3., 4.], 2.5) array([ 0., 0., 1., 1.]) The // operator can be used as a shorthand for np.floor_divide on ndarrays. >>> x1 = np.array([1., 2., 3., 4.]) >>> x1 // 2.5 array([0., 0., 1., 1.])
numpy.reference.generated.numpy.floor_divide
numpy.fmax numpy.fmax(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'fmax'> Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible. Parameters x1, x2array_like The arrays holding the elements to be compared. 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 yndarray or scalar The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. See also fmin Element-wise minimum of two arrays, ignores NaNs. maximum Element-wise maximum of two arrays, propagates NaNs. amax The maximum value of an array along a given axis, propagates NaNs. nanmax The maximum value of an array along a given axis, ignores NaNs. minimum, amin, nanmin Notes New in version 1.3.0. The fmax is equivalent to np.where(x1 >= x2, x1, x2) when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples >>> np.fmax([2, 3, 4], [1, 5, 2]) array([ 2., 5., 4.]) >>> np.fmax(np.eye(2), [0.5, 2]) array([[ 1. , 2. ], [ 0.5, 2. ]]) >>> np.fmax([np.nan, 0, np.nan],[0, np.nan, np.nan]) array([ 0., 0., nan])
numpy.reference.generated.numpy.fmax
numpy.fmin numpy.fmin(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'fmin'> Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are ignored when possible. Parameters x1, x2array_like The arrays holding the elements to be compared. 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 yndarray or scalar The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. See also fmax Element-wise maximum of two arrays, ignores NaNs. minimum Element-wise minimum of two arrays, propagates NaNs. amin The minimum value of an array along a given axis, propagates NaNs. nanmin The minimum value of an array along a given axis, ignores NaNs. maximum, amax, nanmax Notes New in version 1.3.0. The fmin is equivalent to np.where(x1 <= x2, x1, x2) when neither x1 nor x2 are NaNs, but it is faster and does proper broadcasting. Examples >>> np.fmin([2, 3, 4], [1, 5, 2]) array([1, 3, 2]) >>> np.fmin(np.eye(2), [0.5, 2]) array([[ 0.5, 0. ], [ 0. , 1. ]]) >>> np.fmin([np.nan, 0, np.nan],[0, np.nan, np.nan]) array([ 0., 0., nan])
numpy.reference.generated.numpy.fmin
numpy.fmod numpy.fmod(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'fmod'> Returns the element-wise remainder of division. This is the NumPy implementation of the C library function fmod, the remainder has the same sign as the dividend x1. It is equivalent to the Matlab(TM) rem function and should not be confused with the Python modulus operator x1 % x2. Parameters x1array_like Dividend. x2array_like Divisor. 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 yarray_like The remainder of the division of x1 by x2. This is a scalar if both x1 and x2 are scalars. See also remainder Equivalent to the Python % operator. divide Notes The result of the modulo operation for negative dividend and divisors is bound by conventions. For fmod, the sign of result is the sign of the dividend, while for remainder the sign of the result is the sign of the divisor. The fmod function is equivalent to the Matlab(TM) rem function. Examples >>> np.fmod([-3, -2, -1, 1, 2, 3], 2) array([-1, 0, -1, 1, 0, 1]) >>> np.remainder([-3, -2, -1, 1, 2, 3], 2) array([1, 0, 1, 1, 0, 1]) >>> np.fmod([5, 3], [2, 2.]) array([ 1., 1.]) >>> a = np.arange(-3, 3).reshape(3, 2) >>> a array([[-3, -2], [-1, 0], [ 1, 2]]) >>> np.fmod(a, [2,2]) array([[-1, 0], [-1, 0], [ 1, 0]])
numpy.reference.generated.numpy.fmod
numpy.format_float_positional numpy.format_float_positional(x, precision=None, unique=True, fractional=True, trim='k', sign=False, pad_left=None, pad_right=None, min_digits=None)[source] Format a floating-point scalar as a decimal string in positional notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the “Dragon4” algorithm. Parameters xpython float or numpy floating scalar Value to format. precisionnon-negative integer or None, optional Maximum number of digits to print. May be None if unique is True, but must be an integer if unique is False. uniqueboolean, optional If True, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If precision is given fewer digits than necessary can be printed, or if min_digits is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If False, digits are generated as if printing an infinite-precision value and stopping after precision digits, rounding the remaining value with unbiased rounding fractionalboolean, optional If True, the cutoffs of precision and min_digits refer to the total number of digits after the decimal point, including leading zeros. If False, precision and min_digits refer to the total number of significant digits, before or after the decimal point, ignoring leading zeros. trimone of ‘k’, ‘.’, ‘0’, ‘-’, optional Controls post-processing trimming of trailing digits, as follows: ‘k’ : keep trailing zeros, keep decimal point (no trimming) ‘.’ : trim all trailing zeros, leave decimal point ‘0’ : trim all but the zero before the decimal point. Insert the zero if it is missing. ‘-’ : trim trailing zeros and any trailing decimal point signboolean, optional Whether to show the sign for positive values. pad_leftnon-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. pad_rightnon-negative integer, optional Pad the right side of the string with whitespace until at least that many characters are to the right of the decimal point. min_digitsnon-negative integer or None, optional Minimum number of digits to print. Only has an effect if unique=True in which case additional digits past those necessary to uniquely identify the value may be printed, rounding the last additional digit. – versionadded:: 1.21.0 Returns repstring The string representation of the floating point value See also format_float_scientific Examples >>> np.format_float_positional(np.float32(np.pi)) '3.1415927' >>> np.format_float_positional(np.float16(np.pi)) '3.14' >>> np.format_float_positional(np.float16(0.3)) '0.3' >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10) '0.3000488281'
numpy.reference.generated.numpy.format_float_positional
numpy.format_float_scientific numpy.format_float_scientific(x, precision=None, unique=True, trim='k', sign=False, pad_left=None, exp_digits=None, min_digits=None)[source] Format a floating-point scalar as a decimal string in scientific notation. Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the “Dragon4” algorithm. Parameters xpython float or numpy floating scalar Value to format. precisionnon-negative integer or None, optional Maximum number of digits to print. May be None if unique is True, but must be an integer if unique is False. uniqueboolean, optional If True, use a digit-generation strategy which gives the shortest representation which uniquely identifies the floating-point number from other values of the same type, by judicious rounding. If precision is given fewer digits than necessary can be printed. If min_digits is given more can be printed, in which cases the last digit is rounded with unbiased rounding. If False, digits are generated as if printing an infinite-precision value and stopping after precision digits, rounding the remaining value with unbiased rounding trimone of ‘k’, ‘.’, ‘0’, ‘-’, optional Controls post-processing trimming of trailing digits, as follows: ‘k’ : keep trailing zeros, keep decimal point (no trimming) ‘.’ : trim all trailing zeros, leave decimal point ‘0’ : trim all but the zero before the decimal point. Insert the zero if it is missing. ‘-’ : trim trailing zeros and any trailing decimal point signboolean, optional Whether to show the sign for positive values. pad_leftnon-negative integer, optional Pad the left side of the string with whitespace until at least that many characters are to the left of the decimal point. exp_digitsnon-negative integer, optional Pad the exponent with zeros until it contains at least this many digits. If omitted, the exponent will be at least 2 digits. min_digitsnon-negative integer or None, optional Minimum number of digits to print. This only has an effect for unique=True. In that case more digits than necessary to uniquely identify the value may be printed and rounded unbiased. – versionadded:: 1.21.0 Returns repstring The string representation of the floating point value See also format_float_positional Examples >>> np.format_float_scientific(np.float32(np.pi)) '3.1415927e+00' >>> s = np.float32(1.23e24) >>> np.format_float_scientific(s, unique=False, precision=15) '1.230000071797338e+24' >>> np.format_float_scientific(s, exp_digits=4) '1.23e+0024'
numpy.reference.generated.numpy.format_float_scientific
numpy.format_parser class numpy.format_parser(formats, names, titles, aligned=False, byteorder=None)[source] Class to convert formats, names, titles description to a dtype. After constructing the format_parser object, the dtype attribute is the converted data-type: dtype = format_parser(formats, names, titles).dtype Parameters formatsstr or list of str The format description, either specified as a string with comma-separated format descriptions in the form 'f8, i4, a5', or a list of format description strings in the form ['f8', 'i4', 'a5']. namesstr or list/tuple of str The field names, either specified as a comma-separated string in the form 'col1, col2, col3', or as a list or tuple of strings in the form ['col1', 'col2', 'col3']. An empty list can be used, in that case default field names (‘f0’, ‘f1’, …) are used. titlessequence Sequence of title strings. An empty list can be used to leave titles out. alignedbool, optional If True, align the fields by padding as the C-compiler would. Default is False. byteorderstr, optional If specified, all the fields will be changed to the provided byte-order. Otherwise, the default byte-order is used. For all available string specifiers, see dtype.newbyteorder. See also dtype, typename, sctype2char Examples >>> np.format_parser(['<f8', '<i4', '<a5'], ['col1', 'col2', 'col3'], ... ['T1', 'T2', 'T3']).dtype dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4'), (('T3', 'col3'), 'S5')]) names and/or titles can be empty lists. If titles is an empty list, titles will simply not appear. If names is empty, default field names will be used. >>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], ... []).dtype dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '<S5')]) >>> np.format_parser(['<f8', '<i4', '<a5'], [], []).dtype dtype([('f0', '<f8'), ('f1', '<i4'), ('f2', 'S5')]) Attributes dtypedtype The converted data-type.
numpy.reference.generated.numpy.format_parser
numpy.frexp numpy.frexp(x, [out1, out2, ]/, [out=(None, None), ]*, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'frexp'> Decompose the elements of x into mantissa and twos exponent. Returns (mantissa, exponent), where x = mantissa * 2**exponent`. The mantissa lies in the open interval(-1, 1), while the twos exponent is a signed integer. Parameters xarray_like Array of numbers to be decomposed. out1ndarray, optional Output array for the mantissa. Must have the same shape as x. out2ndarray, optional Output array for the exponent. Must have the same shape as x. 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 mantissandarray Floating values between -1 and 1. This is a scalar if x is a scalar. exponentndarray Integer exponents of 2. This is a scalar if x is a scalar. See also ldexp Compute y = x1 * 2**x2, the inverse of frexp. Notes Complex dtypes are not supported, they will raise a TypeError. Examples >>> x = np.arange(9) >>> y1, y2 = np.frexp(x) >>> y1 array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875, 0.5 ]) >>> y2 array([0, 1, 2, 2, 3, 3, 3, 3, 4]) >>> y1 * 2**y2 array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.])
numpy.reference.generated.numpy.frexp
numpy.frombuffer numpy.frombuffer(buffer, dtype=float, count=- 1, offset=0, *, like=None) Interpret a buffer as a 1-dimensional array. Parameters bufferbuffer_like An object that exposes the buffer interface. dtypedata-type, optional Data-type of the returned array; default: float. countint, optional Number of items to read. -1 means all data in the buffer. offsetint, optional Start reading the buffer from this offset (in bytes); default: 0. 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 Notes If the buffer has data that is not in machine byte-order, this should be specified as part of the data-type, e.g.: >>> dt = np.dtype(int) >>> dt = dt.newbyteorder('>') >>> np.frombuffer(buf, dtype=dt) The data of the resulting array will not be byteswapped, but will be interpreted correctly. Examples >>> s = b'hello world' >>> np.frombuffer(s, dtype='S1', count=5, offset=6) array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1') >>> np.frombuffer(b'\x01\x02', dtype=np.uint8) array([1, 2], dtype=uint8) >>> np.frombuffer(b'\x01\x02\x03\x04\x05', dtype=np.uint8, count=3) array([1, 2, 3], dtype=uint8)
numpy.reference.generated.numpy.frombuffer
numpy.fromfile numpy.fromfile(file, dtype=float, count=- 1, sep='', offset=0, *, like=None) Construct an array from data in a text or binary file. A highly efficient way of reading binary data with a known data-type, as well as parsing simply formatted text files. Data written using the tofile method can be read using this function. Parameters filefile or str or Path Open file object or filename. Changed in version 1.17.0: pathlib.Path objects are now accepted. dtypedata-type Data type of the returned array. For binary files, it is used to determine the size and byte-order of the items in the file. Most builtin numeric types are supported and extension types may be supported. New in version 1.18.0: Complex dtypes. countint Number of items to read. -1 means all items (i.e., the complete file). sepstr Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” “) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace. offsetint The offset (in bytes) from the file’s current position. Defaults to 0. Only permitted for binary files. New in version 1.17.0. 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. See also load, save ndarray.tofile loadtxt More flexible way of loading data from a text file. Notes Do not rely on the combination of tofile and fromfile for data storage, as the binary files generated are not platform independent. In particular, no byte-order or data-type information is saved. Data can be stored in the platform independent .npy format using save and load instead. Examples Construct an ndarray: >>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]), ... ('temp', float)]) >>> x = np.zeros((1,), dtype=dt) >>> x['time']['min'] = 10; x['temp'] = 98.25 >>> x array([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')]) Save the raw data to disk: >>> import tempfile >>> fname = tempfile.mkstemp()[1] >>> x.tofile(fname) Read the raw data from disk: >>> np.fromfile(fname, dtype=dt) array([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')]) The recommended way to store and load data: >>> np.save(fname, x) >>> np.load(fname + '.npy') array([((10, 0), 98.25)], dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
numpy.reference.generated.numpy.fromfile
numpy.fromfunction numpy.fromfunction(function, shape, *, dtype=<class 'float'>, like=None, **kwargs)[source] Construct an array by executing a function over each coordinate. The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z). Parameters functioncallable The function is called with N parameters, where N is the rank of shape. Each parameter represents the coordinates of the array varying along a specific axis. For example, if shape were (2, 2), then the parameters would be array([[0, 0], [1, 1]]) and array([[0, 1], [0, 1]]) shape(N,) tuple of ints Shape of the output array, which also determines the shape of the coordinate arrays passed to function. dtypedata-type, optional Data-type of the coordinate arrays passed to function. By default, dtype is float. 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 fromfunctionany The result of the call to function is passed back directly. Therefore the shape of fromfunction is completely determined by function. If function returns a scalar value, the shape of fromfunction would not match the shape parameter. See also indices, meshgrid Notes Keywords other than dtype are passed to function. Examples >>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) array([[ True, False, False], [False, True, False], [False, False, True]]) >>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])
numpy.reference.generated.numpy.fromfunction
numpy.fromiter numpy.fromiter(iter, dtype, count=- 1, *, like=None) Create a new 1-dimensional array from an iterable object. Parameters iteriterable object An iterable object providing data for the array. dtypedata-type The data-type of the returned array. countint, optional The number of items to read from iterable. The default is -1, which means all data is read. 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 output array. Notes Specify count to improve performance. It allows fromiter to pre-allocate the output array, instead of resizing it on demand. Examples >>> iterable = (x*x for x in range(5)) >>> np.fromiter(iterable, float) array([ 0., 1., 4., 9., 16.])
numpy.reference.generated.numpy.fromiter
numpy.frompyfunc numpy.frompyfunc(func, /, nin, nout, *[, identity]) Takes an arbitrary Python function and returns a NumPy ufunc. Can be used, for example, to add broadcasting to a built-in Python function (see Examples section). Parameters funcPython function object An arbitrary Python function. ninint The number of input arguments. noutint The number of objects returned by func. identityobject, optional The value to use for the identity attribute of the resulting object. If specified, this is equivalent to setting the underlying C identity field to PyUFunc_IdentityValue. If omitted, the identity is set to PyUFunc_None. Note that this is _not_ equivalent to setting the identity to None, which implies the operation is reorderable. Returns outufunc Returns a NumPy universal function (ufunc) object. See also vectorize Evaluates pyfunc over input arrays using broadcasting rules of numpy. Notes The returned ufunc always returns PyObject arrays. Examples Use frompyfunc to add broadcasting to the Python function oct: >>> oct_array = np.frompyfunc(oct, 1, 1) >>> oct_array(np.array((10, 30, 100))) array(['0o12', '0o36', '0o144'], dtype=object) >>> np.array((oct(10), oct(30), oct(100))) # for comparison array(['0o12', '0o36', '0o144'], dtype='<U5')
numpy.reference.generated.numpy.frompyfunc
numpy.fromregex numpy.fromregex(file, regexp, dtype, encoding=None)[source] Construct an array from a text file, using regular expression parsing. The returned array is always a structured array, and is constructed from all matches of the regular expression in the file. Groups in the regular expression are converted to fields of the structured array. Parameters filepath or file Filename or file object to read. Changed in version 1.22.0: Now accepts os.PathLike implementations. regexpstr or regexp Regular expression used to parse the file. Groups in the regular expression correspond to fields in the dtype. dtypedtype or list of dtypes Dtype for the structured array; must be a structured datatype. encodingstr, optional Encoding used to decode the inputfile. Does not apply to input streams. New in version 1.14.0. Returns outputndarray The output array, containing the part of the content of file that was matched by regexp. output is always a structured array. Raises TypeError When dtype is not a valid dtype for a structured array. See also fromstring, loadtxt Notes Dtypes for structured arrays can be specified in several forms, but all forms specify at least the data type and field name. For details see basics.rec. Examples >>> from io import StringIO >>> text = StringIO("1312 foo\n1534 bar\n444 qux") >>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything] >>> output = np.fromregex(text, regexp, ... [('num', np.int64), ('key', 'S3')]) >>> output array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')], dtype=[('num', '<i8'), ('key', 'S3')]) >>> output['num'] array([1312, 1534, 444])
numpy.reference.generated.numpy.fromregex
numpy.fromstring numpy.fromstring(string, dtype=float, count=- 1, *, sep, like=None) A new 1-D array initialized from text data in a string. Parameters stringstr A string containing the data. dtypedata-type, optional The data type of the array; default: float. For binary input data, the data must be in exactly this format. Most builtin numeric types are supported and extension types may be supported. New in version 1.18.0: Complex dtypes. countint, optional Read this number of dtype elements from the data. If this is negative (the default), the count will be determined from the length of the data. sepstr, optional The string separating numbers in the data; extra whitespace between elements is also ignored. Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results. 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 arrndarray The constructed array. Raises ValueError If the string is not the correct size to satisfy the requested dtype and count. See also frombuffer, fromfile, fromiter Examples >>> np.fromstring('1 2', dtype=int, sep=' ') array([1, 2]) >>> np.fromstring('1, 2', dtype=int, sep=',') array([1, 2])
numpy.reference.generated.numpy.fromstring
numpy.full numpy.full(shape, fill_value, dtype=None, order='C', *, like=None)[source] Return a new array of given shape and type, filled with fill_value. Parameters shapeint or sequence of ints Shape of the new array, e.g., (2, 3) or 2. fill_valuescalar or array_like Fill value. dtypedata-type, optional The desired data-type for the array The default, None, means np.array(fill_value).dtype. order{‘C’, ‘F’}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. 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 of fill_value with the given shape, dtype, and order. See also 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. Examples >>> np.full((2, 2), np.inf) array([[inf, inf], [inf, inf]]) >>> np.full((2, 2), 10) array([[10, 10], [10, 10]]) >>> np.full((2, 2), [1, 2]) array([[1, 2], [1, 2]])
numpy.reference.generated.numpy.full
numpy.full_like numpy.full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None)[source] Return a full array with the same shape and type as a given array. Parameters aarray_like The shape and data-type of a define these same attributes of the returned array. fill_valuescalar Fill value. dtypedata-type, optional Overrides the data type of the result. order{‘C’, ‘F’, ‘A’, or ‘K’}, optional Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. subokbool, optional. If True, then the newly created array will use the sub-class type of a, otherwise it will be a base-class array. Defaults to True. shapeint or sequence of ints, optional. Overrides the shape of the result. If order=’K’ and the number of dimensions is unchanged, will try to keep order, otherwise, order=’C’ is implied. New in version 1.17.0. Returns outndarray Array of fill_value with the same shape and type as a. 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 Return a new array of given shape filled with value. Examples >>> x = np.arange(6, dtype=int) >>> np.full_like(x, 1) array([1, 1, 1, 1, 1, 1]) >>> np.full_like(x, 0.1) array([0, 0, 0, 0, 0, 0]) >>> np.full_like(x, 0.1, dtype=np.double) array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) >>> np.full_like(x, np.nan, dtype=np.double) array([nan, nan, nan, nan, nan, nan]) >>> y = np.arange(6, dtype=np.double) >>> np.full_like(y, 0.1) array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
numpy.reference.generated.numpy.full_like
numpy.gcd numpy.gcd(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'gcd'> Returns the greatest common divisor of |x1| and |x2| Parameters x1, x2array_like, int Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). Returns yndarray or scalar The greatest common divisor of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars. See also lcm The lowest common multiple Examples >>> np.gcd(12, 20) 4 >>> np.gcd.reduce([15, 25, 35]) 5 >>> np.gcd(np.arange(6), 20) array([20, 1, 2, 1, 4, 5])
numpy.reference.generated.numpy.gcd
numpy.genfromtxt numpy.genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=" !#$%&'()*+, -./:;<=>?@[\\]^{|}~", replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding='bytes', *, like=None)[source] Load data from a text file, with missing values handled as specified. Each line past the first skip_header lines is split at the delimiter character, and characters following the comments character are discarded. Parameters fnamefile, str, pathlib.Path, list of str, generator File, filename, list, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators must return bytes or strings. The strings in a list or produced by a generator are treated as lines. dtypedtype, optional Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. commentsstr, optional The character used to indicate the start of a comment. All the characters occurring on a line after a comment are discarded. delimiterstr, int, or sequence, optional The string used to separate values. By default, any consecutive whitespaces act as delimiter. An integer or sequence of integers can also be provided as width(s) of each field. skiprowsint, optional skiprows was removed in numpy 1.10. Please use skip_header instead. skip_headerint, optional The number of lines to skip at the beginning of the file. skip_footerint, optional The number of lines to skip at the end of the file. convertersvariable, optional The set of functions that convert the data of a column to a value. The converters can also be used to provide a default value for missing data: converters = {3: lambda s: float(s or 0)}. missingvariable, optional missing was removed in numpy 1.10. Please use missing_values instead. missing_valuesvariable, optional The set of strings corresponding to missing data. filling_valuesvariable, optional The set of values to be used as default when the data are missing. usecolssequence, optional Which columns to read, with 0 being the first. For example, usecols = (1, 4, 5) will extract the 2nd, 5th and 6th columns. names{None, True, str, sequence}, optional If names is True, the field names are read from the first line after the first skip_header lines. This line can optionally be preceded by a comment delimiter. If names is a sequence or a single-string of comma-separated names, the names will be used to define the field names in a structured dtype. If names is None, the names of the dtype fields will be used, if any. excludelistsequence, optional A list of names to exclude. This list is appended to the default list [‘return’,’file’,’print’]. Excluded names are appended with an underscore: for example, file would become file_. deletecharsstr, optional A string combining invalid characters that must be deleted from the names. defaultfmtstr, optional A format used to define default field names, such as “f%i” or “f_%02i”. autostripbool, optional Whether to automatically strip white spaces from the variables. replace_spacechar, optional Character(s) used in replacement of white spaces in the variable names. By default, use a ‘_’. case_sensitive{True, False, ‘upper’, ‘lower’}, optional If True, field names are case sensitive. If False or ‘upper’, field names are converted to upper case. If ‘lower’, field names are converted to lower case. unpackbool, optional If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = genfromtxt(...). When used with a structured data-type, arrays are returned for each field. Default is False. usemaskbool, optional If True, return a masked array. If False, return a regular array. loosebool, optional If True, do not raise errors for invalid values. invalid_raisebool, optional If True, an exception is raised if an inconsistency is detected in the number of columns. If False, a warning is emitted and the offending lines are skipped. max_rowsint, optional The maximum number of rows to read. Must not be used with skip_footer at the same time. If given, the value must be at least 1. Default is to read the entire file. New in version 1.10.0. encodingstr, optional Encoding used to decode the inputfile. Does not apply when fname is a file object. The special value ‘bytes’ enables backward compatibility workarounds that ensure that you receive byte arrays when possible and passes latin1 encoded strings to converters. Override this value to receive unicode arrays and pass strings as input to converters. If set to None the system default is used. The default value is ‘bytes’. New in version 1.14.0. 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 Data read from the text file. If usemask is True, this is a masked array. See also numpy.loadtxt equivalent function when no data is missing. Notes When spaces are used as delimiters, or when no delimiter has been given as input, there should not be any missing data between two fields. When the variables are named (either by a flexible dtype or with names), there must not be any header in the file (else a ValueError exception is raised). Individual values are not stripped of spaces by default. When using a custom converter, make sure the function does remove spaces. References 1 NumPy User Guide, section I/O with NumPy. Examples >>> from io import StringIO >>> import numpy as np Comma delimited file with mixed dtype >>> s = StringIO(u"1,1.3,abcde") >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), ... ('mystring','S5')], delimiter=",") >>> data array((1, 1.3, b'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')]) Using dtype = None >>> _ = s.seek(0) # needed for StringIO example only >>> data = np.genfromtxt(s, dtype=None, ... names = ['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, b'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')]) Specifying dtype and names >>> _ = s.seek(0) >>> data = np.genfromtxt(s, dtype="i8,f8,S5", ... names=['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, b'abcde'), dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')]) An example with fixed-width columns >>> s = StringIO(u"11.3abcde") >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'], ... delimiter=[1,3,5]) >>> data array((1, 1.3, b'abcde'), dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', 'S5')]) An example to show comments >>> f = StringIO(''' ... text,# of chars ... hello world,11 ... numpy,5''') >>> np.genfromtxt(f, dtype='S12,S12', delimiter=',') array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')], dtype=[('f0', 'S12'), ('f1', 'S12')])
numpy.reference.generated.numpy.genfromtxt
numpy.geomspace numpy.geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)[source] Return numbers spaced evenly on a log scale (a geometric progression). This is similar to logspace, but with endpoints specified directly. Each output sample is a constant multiple of the previous. Changed in version 1.16.0: Non-scalar start and stop are now supported. Parameters startarray_like The starting value of the sequence. stoparray_like The final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned. numinteger, optional Number of samples to generate. Default is 50. endpointboolean, optional If true, stop is the last sample. Otherwise, it is not included. Default is True. dtypedtype The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred dtype will never be an integer; float is chosen even if the arguments would produce an array of integers. axisint, optional The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end. New in version 1.16.0. Returns samplesndarray num samples, equally spaced on a log scale. See also logspace Similar to geomspace, but with endpoints specified using log and base. linspace Similar to geomspace, but with arithmetic instead of geometric progression. arange Similar to linspace, with the step size specified instead of the number of samples. Notes If the inputs or dtype are complex, the output will follow a logarithmic spiral in the complex plane. (There are an infinite number of spirals passing through two points; the output will follow the shortest such path.) Examples >>> np.geomspace(1, 1000, num=4) array([ 1., 10., 100., 1000.]) >>> np.geomspace(1, 1000, num=3, endpoint=False) array([ 1., 10., 100.]) >>> np.geomspace(1, 1000, num=4, endpoint=False) array([ 1. , 5.62341325, 31.6227766 , 177.827941 ]) >>> np.geomspace(1, 256, num=9) array([ 1., 2., 4., 8., 16., 32., 64., 128., 256.]) Note that the above may not produce exact integers: >>> np.geomspace(1, 256, num=9, dtype=int) array([ 1, 2, 4, 7, 16, 32, 63, 127, 256]) >>> np.around(np.geomspace(1, 256, num=9)).astype(int) array([ 1, 2, 4, 8, 16, 32, 64, 128, 256]) Negative, decreasing, and complex inputs are allowed: >>> np.geomspace(1000, 1, num=4) array([1000., 100., 10., 1.]) >>> np.geomspace(-1000, -1, num=4) array([-1000., -100., -10., -1.]) >>> np.geomspace(1j, 1000j, num=4) # Straight line array([0. +1.j, 0. +10.j, 0. +100.j, 0.+1000.j]) >>> np.geomspace(-1+0j, 1+0j, num=5) # Circle array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j, 6.12323400e-17+1.00000000e+00j, 7.07106781e-01+7.07106781e-01j, 1.00000000e+00+0.00000000e+00j]) Graphical illustration of endpoint parameter: >>> import matplotlib.pyplot as plt >>> N = 10 >>> y = np.zeros(N) >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=True), y + 1, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=False), y + 2, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.axis([0.5, 2000, 0, 3]) [0.5, 2000, 0, 3] >>> plt.grid(True, color='0.7', linestyle='-', which='both', axis='both') >>> plt.show()
numpy.reference.generated.numpy.geomspace
numpy.get_include numpy.get_include()[source] Return the directory that contains the NumPy *.h header files. Extension modules that need to compile against NumPy should use this function to locate the appropriate include directory. Notes When using distutils, for example in setup.py. import numpy as np ... Extension('extension_name', ... include_dirs=[np.get_include()]) ...
numpy.reference.generated.numpy.get_include
numpy.get_printoptions numpy.get_printoptions()[source] Return the current print options. Returns print_optsdict Dictionary of current print options with keys precision : int threshold : int edgeitems : int linewidth : int suppress : bool nanstr : str infstr : str formatter : dict of callables sign : str For a full description of these options, see set_printoptions. See also set_printoptions, printoptions, set_string_function
numpy.reference.generated.numpy.get_printoptions
numpy.getbufsize numpy.getbufsize()[source] Return the size of the buffer used in ufuncs. Returns getbufsizeint Size of ufunc buffer in bytes.
numpy.reference.generated.numpy.getbufsize
numpy.geterr numpy.geterr()[source] Get the current way of handling floating-point errors. Returns resdict A dictionary with keys “divide”, “over”, “under”, and “invalid”, whose values are from the strings “ignore”, “print”, “log”, “warn”, “raise”, and “call”. The keys represent possible floating-point exceptions, and the values define how these exceptions are handled. See also geterrcall, seterr, seterrcall Notes For complete documentation of the types of floating-point exceptions and treatment options, see seterr. Examples >>> np.geterr() {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'} >>> np.arange(3.) / np.arange(3.) array([nan, 1., 1.]) >>> oldsettings = np.seterr(all='warn', over='raise') >>> np.geterr() {'divide': 'warn', 'over': 'raise', 'under': 'warn', 'invalid': 'warn'} >>> np.arange(3.) / np.arange(3.) array([nan, 1., 1.])
numpy.reference.generated.numpy.geterr
numpy.geterrcall numpy.geterrcall()[source] Return the current callback function used on floating-point errors. When the error handling for a floating-point error (one of “divide”, “over”, “under”, or “invalid”) is set to ‘call’ or ‘log’, the function that is called or the log instance that is written to is returned by geterrcall. This function or log instance has been set with seterrcall. Returns errobjcallable, log instance or None The current error handler. If no handler was set through seterrcall, None is returned. See also seterrcall, seterr, geterr Notes For complete documentation of the types of floating-point exceptions and treatment options, see seterr. Examples >>> np.geterrcall() # we did not yet set a handler, returns None >>> oldsettings = np.seterr(all='call') >>> def err_handler(type, flag): ... print("Floating point error (%s), with flag %s" % (type, flag)) >>> oldhandler = np.seterrcall(err_handler) >>> np.array([1, 2, 3]) / 0.0 Floating point error (divide by zero), with flag 1 array([inf, inf, inf]) >>> cur_handler = np.geterrcall() >>> cur_handler is err_handler True
numpy.reference.generated.numpy.geterrcall
numpy.geterrobj numpy.geterrobj() Return the current object that defines floating-point error handling. The error object contains all information that defines the error handling behavior in NumPy. geterrobj is used internally by the other functions that get and set error handling behavior (geterr, seterr, geterrcall, seterrcall). Returns errobjlist The error object, a list containing three elements: [internal numpy buffer size, error mask, error callback function]. The error mask is a single integer that holds the treatment information on all four floating point errors. The information for each error type is contained in three bits of the integer. If we print it in base 8, we can see what treatment is set for “invalid”, “under”, “over”, and “divide” (in that order). The printed string can be interpreted with 0 : ‘ignore’ 1 : ‘warn’ 2 : ‘raise’ 3 : ‘call’ 4 : ‘print’ 5 : ‘log’ See also seterrobj, seterr, geterr, seterrcall, geterrcall getbufsize, setbufsize Notes For complete documentation of the types of floating-point exceptions and treatment options, see seterr. Examples >>> np.geterrobj() # first get the defaults [8192, 521, None] >>> def err_handler(type, flag): ... print("Floating point error (%s), with flag %s" % (type, flag)) ... >>> old_bufsize = np.setbufsize(20000) >>> old_err = np.seterr(divide='raise') >>> old_handler = np.seterrcall(err_handler) >>> np.geterrobj() [8192, 521, <function err_handler at 0x91dcaac>] >>> old_err = np.seterr(all='ignore') >>> np.base_repr(np.geterrobj()[1], 8) '0' >>> old_err = np.seterr(divide='warn', over='log', under='call', ... invalid='print') >>> np.base_repr(np.geterrobj()[1], 8) '4351'
numpy.reference.generated.numpy.geterrobj
numpy.gradient numpy.gradient(f, *varargs, axis=None, edge_order=1)[source] Return the gradient of an N-dimensional array. The gradient is computed using second order accurate central differences in the interior points and either first or second order accurate one-sides (forward or backwards) differences at the boundaries. The returned gradient hence has the same shape as the input array. Parameters farray_like An N-dimensional array containing samples of a scalar function. varargslist of scalar or array, optional Spacing between f values. Default unitary spacing for all dimensions. Spacing can be specified using: single scalar to specify a sample distance for all dimensions. N scalars to specify a constant sample distance for each dimension. i.e. dx, dy, dz, … N arrays to specify the coordinates of the values along each dimension of F. The length of the array must match the size of the corresponding dimension Any combination of N scalars/arrays with the meaning of 2. and 3. If axis is given, the number of varargs must equal the number of axes. Default: 1. edge_order{1, 2}, optional Gradient is calculated using N-th order accurate differences at the boundaries. Default: 1. New in version 1.9.1. axisNone or int or tuple of ints, optional Gradient is calculated only along the given axis or axes The default (axis = None) is to calculate the gradient for all the axes of the input array. axis may be negative, in which case it counts from the last to the first axis. New in version 1.11.0. Returns gradientndarray or list of ndarray A list of ndarrays (or a single ndarray if there is only one dimension) corresponding to the derivatives of f with respect to each dimension. Each derivative has the same shape as f. Notes Assuming that \(f\in C^{3}\) (i.e., \(f\) has at least 3 continuous derivatives) and let \(h_{*}\) be a non-homogeneous stepsize, we minimize the “consistency error” \(\eta_{i}\) between the true gradient and its estimate from a linear combination of the neighboring grid-points: \[\eta_{i} = f_{i}^{\left(1\right)} - \left[ \alpha f\left(x_{i}\right) + \beta f\left(x_{i} + h_{d}\right) + \gamma f\left(x_{i}-h_{s}\right) \right]\] By substituting \(f(x_{i} + h_{d})\) and \(f(x_{i} - h_{s})\) with their Taylor series expansion, this translates into solving the following the linear system: \[\begin{split}\left\{ \begin{array}{r} \alpha+\beta+\gamma=0 \\ \beta h_{d}-\gamma h_{s}=1 \\ \beta h_{d}^{2}+\gamma h_{s}^{2}=0 \end{array} \right.\end{split}\] The resulting approximation of \(f_{i}^{(1)}\) is the following: \[\hat f_{i}^{(1)} = \frac{ h_{s}^{2}f\left(x_{i} + h_{d}\right) + \left(h_{d}^{2} - h_{s}^{2}\right)f\left(x_{i}\right) - h_{d}^{2}f\left(x_{i}-h_{s}\right)} { h_{s}h_{d}\left(h_{d} + h_{s}\right)} + \mathcal{O}\left(\frac{h_{d}h_{s}^{2} + h_{s}h_{d}^{2}}{h_{d} + h_{s}}\right)\] It is worth noting that if \(h_{s}=h_{d}\) (i.e., data are evenly spaced) we find the standard second order approximation: \[\hat f_{i}^{(1)}= \frac{f\left(x_{i+1}\right) - f\left(x_{i-1}\right)}{2h} + \mathcal{O}\left(h^{2}\right)\] With a similar procedure the forward/backward approximations used for boundaries can be derived. References 1 Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics (Texts in Applied Mathematics). New York: Springer. 2 Durran D. R. (1999) Numerical Methods for Wave Equations in Geophysical Fluid Dynamics. New York: Springer. 3 Fornberg B. (1988) Generation of Finite Difference Formulas on Arbitrarily Spaced Grids, Mathematics of Computation 51, no. 184 : 699-706. PDF. Examples >>> f = np.array([1, 2, 4, 7, 11, 16], dtype=float) >>> np.gradient(f) array([1. , 1.5, 2.5, 3.5, 4.5, 5. ]) >>> np.gradient(f, 2) array([0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ]) Spacing can be also specified with an array that represents the coordinates of the values F along the dimensions. For instance a uniform spacing: >>> x = np.arange(f.size) >>> np.gradient(f, x) array([1. , 1.5, 2.5, 3.5, 4.5, 5. ]) Or a non uniform one: >>> x = np.array([0., 1., 1.5, 3.5, 4., 6.], dtype=float) >>> np.gradient(f, x) array([1. , 3. , 3.5, 6.7, 6.9, 2.5]) For two dimensional arrays, the return will be two arrays ordered by axis. In this example the first array stands for the gradient in rows and the second one in columns direction: >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float)) [array([[ 2., 2., -1.], [ 2., 2., -1.]]), array([[1. , 2.5, 4. ], [1. , 1. , 1. ]])] In this example the spacing is also specified: uniform for axis=0 and non uniform for axis=1 >>> dx = 2. >>> y = [1., 1.5, 3.5] >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), dx, y) [array([[ 1. , 1. , -0.5], [ 1. , 1. , -0.5]]), array([[2. , 2. , 2. ], [2. , 1.7, 0.5]])] It is possible to specify how boundaries are treated using edge_order >>> x = np.array([0, 1, 2, 3, 4]) >>> f = x**2 >>> np.gradient(f, edge_order=1) array([1., 2., 4., 6., 7.]) >>> np.gradient(f, edge_order=2) array([0., 2., 4., 6., 8.]) The axis keyword can be used to specify a subset of axes of which the gradient is calculated >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), axis=0) array([[ 2., 2., -1.], [ 2., 2., -1.]])
numpy.reference.generated.numpy.gradient
numpy.greater numpy.greater(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'greater'> Return the truth value of (x1 > x2) element-wise. Parameters x1, x2array_like Input arrays. 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 outndarray or scalar Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. See also greater_equal, less, less_equal, equal, not_equal Examples >>> np.greater([4,2],[2,2]) array([ True, False]) The > operator can be used as a shorthand for np.greater on ndarrays. >>> a = np.array([4, 2]) >>> b = np.array([2, 2]) >>> a > b array([ True, False])
numpy.reference.generated.numpy.greater
numpy.greater_equal numpy.greater_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'greater_equal'> Return the truth value of (x1 >= x2) element-wise. Parameters x1, x2array_like Input arrays. 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 outbool or ndarray of bool Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. See also greater, less, less_equal, equal, not_equal Examples >>> np.greater_equal([4, 2, 1], [2, 2, 2]) array([ True, True, False]) The >= operator can be used as a shorthand for np.greater_equal on ndarrays. >>> a = np.array([4, 2, 1]) >>> b = np.array([2, 2, 2]) >>> a >= b array([ True, True, False])
numpy.reference.generated.numpy.greater_equal
class numpy.half[source] Half-precision floating-point number type. Character code 'e' Alias on this platform (Linux x86_64) numpy.float16: 16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa.
numpy.reference.arrays.scalars#numpy.half
numpy.hamming numpy.hamming(M)[source] Return the Hamming window. The Hamming window is a taper formed by using a weighted cosine. Parameters Mint Number of points in the output window. If zero or less, an empty array is returned. Returns outndarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See also bartlett, blackman, hanning, kaiser Notes The Hamming window is defined as \[w(n) = 0.54 - 0.46cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1\] The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and is described in Blackman and Tukey. It was recommended for smoothing the truncated autocovariance function in the time domain. Most references to the Hamming window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. 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. References 1 Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. 2 E.R. Kanasewich, “Time Sequence Analysis in Geophysics”, The University of Alberta Press, 1975, pp. 109-110. 3 Wikipedia, “Window function”, https://en.wikipedia.org/wiki/Window_function 4 W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, “Numerical Recipes”, Cambridge University Press, 1986, page 425. Examples >>> np.hamming(12) array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594, # may vary 0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909, 0.15302337, 0.08 ]) Plot the window and the frequency response: >>> import matplotlib.pyplot as plt >>> from numpy.fft import fft, fftshift >>> window = np.hamming(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hamming window") Text(0.5, 1.0, 'Hamming 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)) >>> 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 Hamming window") Text(0.5, 1.0, 'Frequency response of Hamming 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.hamming
numpy.hanning numpy.hanning(M)[source] Return the Hanning window. The Hanning window is a taper formed by using a weighted cosine. Parameters Mint Number of points in the output window. If zero or less, an empty array is returned. Returns outndarray, shape(M,) The window, with the maximum value normalized to one (the value one appears only if M is odd). See also bartlett, blackman, hamming, kaiser Notes The Hanning window is defined as \[w(n) = 0.5 - 0.5cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1\] The Hanning was named for Julius von Hann, an Austrian meteorologist. It is also known as the Cosine Bell. Some authors prefer that it be called a Hann window, to help avoid confusion with the very similar Hamming window. Most references to the Hanning window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. 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. References 1 Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. 2 E.R. Kanasewich, “Time Sequence Analysis in Geophysics”, The University of Alberta Press, 1975, pp. 106-108. 3 Wikipedia, “Window function”, https://en.wikipedia.org/wiki/Window_function 4 W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, “Numerical Recipes”, Cambridge University Press, 1986, page 425. Examples >>> np.hanning(12) array([0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037, 0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249, 0.07937323, 0. ]) Plot the window and its frequency response: >>> import matplotlib.pyplot as plt >>> from numpy.fft import fft, fftshift >>> window = np.hanning(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Hann window") Text(0.5, 1.0, 'Hann 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 the Hann window") Text(0.5, 1.0, 'Frequency response of the Hann 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.hanning
numpy.heaviside numpy.heaviside(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'heaviside'> Compute the Heaviside step function. The Heaviside step function is defined as: 0 if x1 < 0 heaviside(x1, x2) = x2 if x1 == 0 1 if x1 > 0 where x2 is often taken to be 0.5, but 0 and 1 are also sometimes used. Parameters x1array_like Input values. x2array_like The value of the function when x1 is 0. 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 outndarray or scalar The output array, element-wise Heaviside step function of x1. This is a scalar if both x1 and x2 are scalars. Notes New in version 1.13.0. References Examples >>> np.heaviside([-1.5, 0, 2.0], 0.5) array([ 0. , 0.5, 1. ]) >>> np.heaviside([-1.5, 0, 2.0], 1) array([ 0., 1., 1.])
numpy.reference.generated.numpy.heaviside
numpy.histogram numpy.histogram(a, bins=10, range=None, normed=None, weights=None, density=None)[source] Compute the histogram of a dataset. Parameters aarray_like Input data. The histogram is computed over the flattened array. binsint or sequence of scalars or str, optional If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform bin widths. New in version 1.11.0. If bins is a string, it defines the method used to calculate the optimal bin width, as defined by histogram_bin_edges. range(float, float), optional The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. The first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data. normedbool, optional Deprecated since version 1.6.0. This is equivalent to the density argument, but produces incorrect results for unequal bin widths. It should not be used. Changed in version 1.15.0: DeprecationWarnings are actually emitted. weightsarray_like, optional An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). If density is True, the weights are normalized, so that the integral of the density over the range remains 1. densitybool, optional If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function. Overrides the normed keyword if given. Returns histarray The values of the histogram. See density and weights for a description of the possible semantics. bin_edgesarray of dtype float Return the bin edges (length(hist)+1). See also histogramdd, bincount, searchsorted, digitize, histogram_bin_edges Notes All but the last (righthand-most) bin is half-open. In other words, if bins is: [1, 2, 3, 4] then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is [3, 4], which includes 4. Examples >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3]) (array([0, 2, 1]), array([0, 1, 2, 3])) >>> np.histogram(np.arange(4), bins=np.arange(5), density=True) (array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) (array([1, 4, 1]), array([0, 1, 2, 3])) >>> a = np.arange(5) >>> hist, bin_edges = np.histogram(a, density=True) >>> hist array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]) >>> hist.sum() 2.4999999999999996 >>> np.sum(hist * np.diff(bin_edges)) 1.0 New in version 1.11.0. Automated Bin Selection Methods example, using 2 peak random data with 2000 points: >>> import matplotlib.pyplot as plt >>> rng = np.random.RandomState(10) # deterministic random data >>> a = np.hstack((rng.normal(size=1000), ... rng.normal(loc=5, scale=2, size=1000))) >>> _ = plt.hist(a, bins='auto') # arguments are passed to np.histogram >>> plt.title("Histogram with 'auto' bins") Text(0.5, 1.0, "Histogram with 'auto' bins") >>> plt.show()
numpy.reference.generated.numpy.histogram