doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.matrix.sum method matrix.sum(axis=None, dtype=None, out=None)[source] Returns the sum of the matrix elements, along the given axis. Refer to numpy.sum for full documentation. See also numpy.sum Notes This is the same as ndarray.sum, except that where an ndarray would be returned, a matrix object is returned instead. Examples >>> x = np.matrix([[1, 2], [4, 3]]) >>> x.sum() 10 >>> x.sum(axis=1) matrix([[3], [7]]) >>> x.sum(axis=1, dtype='float') matrix([[3.], [7.]]) >>> out = np.zeros((2, 1), dtype='float') >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out)) matrix([[3.], [7.]])
numpy.reference.generated.numpy.matrix.sum
numpy.matrix.swapaxes method matrix.swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged. Refer to numpy.swapaxes for full documentation. See also numpy.swapaxes equivalent function
numpy.reference.generated.numpy.matrix.swapaxes
numpy.matrix.take method matrix.take(indices, axis=None, out=None, mode='raise') Return an array formed from the elements of a at the given indices. Refer to numpy.take for full documentation. See also numpy.take equivalent function
numpy.reference.generated.numpy.matrix.take
numpy.matrix.tobytes method matrix.tobytes(order='C') Construct Python bytes containing the raw data bytes in the array. Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter. New in version 1.9.0. Parameters order{‘C’, ‘F’, ‘A’}, optional Controls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’. Returns sbytes Python bytes exhibiting a copy of a’s raw data. Examples >>> x = np.array([[0, 1], [2, 3]], dtype='<u2') >>> x.tobytes() b'\x00\x00\x01\x00\x02\x00\x03\x00' >>> x.tobytes('C') == x.tobytes() True >>> x.tobytes('F') b'\x00\x00\x02\x00\x01\x00\x03\x00'
numpy.reference.generated.numpy.matrix.tobytes
numpy.matrix.tofile method matrix.tofile(fid, sep='', format='%s') Write array to a file as text or binary (default). Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile(). Parameters fidfile or str or Path An open file object, or a string containing a filename. Changed in version 1.17.0: pathlib.Path objects are now accepted. sepstr Separator between array items for text output. If “” (empty), a binary file is written, equivalent to file.write(a.tobytes()). formatstr Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using “format” % item. Notes This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size. When fid is a file object, array contents are directly written to the file, bypassing the file object’s write method. As a result, tofile cannot be used with files objects supporting compression (e.g., GzipFile) or file-like objects that do not support fileno() (e.g., BytesIO).
numpy.reference.generated.numpy.matrix.tofile
numpy.matrix.tolist method matrix.tolist()[source] Return the matrix as a (possibly nested) list. See ndarray.tolist for full documentation. See also ndarray.tolist Examples >>> x = np.matrix(np.arange(12).reshape((3,4))); x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.tolist() [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
numpy.reference.generated.numpy.matrix.tolist
numpy.matrix.tostring method matrix.tostring(order='C') A compatibility alias for tobytes, with exactly the same behavior. Despite its name, it returns bytes not strs. Deprecated since version 1.19.0.
numpy.reference.generated.numpy.matrix.tostring
numpy.matrix.trace method matrix.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) Return the sum along diagonals of the array. Refer to numpy.trace for full documentation. See also numpy.trace equivalent function
numpy.reference.generated.numpy.matrix.trace
numpy.matrix.transpose method matrix.transpose(*axes) Returns a view of the array with axes transposed. For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]). Parameters axesNone, tuple of ints, or n ints None or no argument: reverses the order of the axes. tuple of ints: i in the j-th place in the tuple means a’s i-th axis becomes a.transpose()’s j-th axis. n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form) Returns outndarray View of a, with axes suitably permuted. See also transpose Equivalent function ndarray.T Array property returning the array transposed. ndarray.reshape Give a new shape to an array without changing its data. Examples >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.transpose() array([[1, 3], [2, 4]]) >>> a.transpose((1, 0)) array([[1, 3], [2, 4]]) >>> a.transpose(1, 0) array([[1, 3], [2, 4]])
numpy.reference.generated.numpy.matrix.transpose
numpy.matrix.var method matrix.var(axis=None, dtype=None, out=None, ddof=0)[source] Returns the variance of the matrix elements, along the given axis. Refer to numpy.var for full documentation. See also numpy.var Notes This is the same as ndarray.var, except that where an ndarray would be returned, a matrix object is returned instead. Examples >>> x = np.matrix(np.arange(12).reshape((3, 4))) >>> x matrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> x.var() 11.916666666666666 >>> x.var(0) matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary >>> x.var(1) matrix([[1.25], [1.25], [1.25]])
numpy.reference.generated.numpy.matrix.var
numpy.matrix.view method matrix.view([dtype][, type]) New view of array with the same data. Note Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_'). Parameters dtypedata-type or ndarray sub-class, optional Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter). typePython type, optional Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation. Notes a.view() is used two different ways: a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory. a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results. Examples >>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) Viewing array data using a different type and dtype: >>> y = x.view(dtype=np.int16, type=np.matrix) >>> y matrix([[513]], dtype=int16) >>> print(type(y)) <class 'numpy.matrix'> Creating a view on a structured array so it can be used in calculations >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) >>> xv = x.view(dtype=np.int8).reshape(-1,2) >>> xv array([[1, 2], [3, 4]], dtype=int8) >>> xv.mean(0) array([2., 3.]) Making changes to the view changes the underlying array >>> xv[0,1] = 20 >>> x array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')]) Using a view to convert an array to a recarray: >>> z = x.view(np.recarray) >>> z.a array([1, 3], dtype=int8) Views share data: >>> x[0] = (9, 10) >>> z[0] (9, 10) Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.: >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16) >>> y = x[:, 0:2] >>> y array([[1, 2], [4, 5]], dtype=int16) >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) Traceback (most recent call last): ... ValueError: To change to a dtype of a different size, the array must be C-contiguous >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 2)], [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')])
numpy.reference.generated.numpy.matrix.view
numpy.memmap.flush method memmap.flush()[source] Write any changes in the array to the file on disk. For further information, see memmap. Parameters None See also memmap
numpy.reference.generated.numpy.memmap.flush
Miscellaneous IEEE 754 Floating Point Special Values Special values defined in numpy: nan, inf, NaNs can be used as a poor-man’s mask (if you don’t care what the original value was) Note: cannot use equality to test NaNs. E.g.: >>> myarr = np.array([1., 0., np.nan, 3.]) >>> np.nonzero(myarr == np.nan) (array([], dtype=int64),) >>> np.nan == np.nan # is always False! Use special numpy functions instead. False >>> myarr[myarr == np.nan] = 0. # doesn't work >>> myarr array([ 1., 0., NaN, 3.]) >>> myarr[np.isnan(myarr)] = 0. # use this instead find >>> myarr array([ 1., 0., 0., 3.]) Other related special value functions: isinf(): True if value is inf isfinite(): True if not nan or inf nan_to_num(): Map nan to 0, inf to max float, -inf to min float The following corresponds to the usual functions except that nans are excluded from the results: nansum() nanmax() nanmin() nanargmax() nanargmin() >>> x = np.arange(10.) >>> x[3] = np.nan >>> x.sum() nan >>> np.nansum(x) 42.0 How numpy handles numerical exceptions The default is to 'warn' for invalid, divide, and overflow and 'ignore' for underflow. But this can be changed, and it can be set individually for different kinds of exceptions. The different behaviors are: ‘ignore’ : Take no action when the exception occurs. ‘warn’ : Print a RuntimeWarning (via the Python warnings module). ‘raise’ : Raise a FloatingPointError. ‘call’ : Call a function specified using the seterrcall function. ‘print’ : Print a warning directly to stdout. ‘log’ : Record error in a Log object specified by seterrcall. These behaviors can be set for all kinds of errors or specific ones: all : apply to all numeric exceptions invalid : when NaNs are generated divide : divide by zero (for integers as well!) overflow : floating point overflows underflow : floating point underflows Note that integer divide-by-zero is handled by the same machinery. These behaviors are set on a per-thread basis. Examples >>> oldsettings = np.seterr(all='warn') >>> np.zeros(5,dtype=np.float32)/0. invalid value encountered in divide >>> j = np.seterr(under='ignore') >>> np.array([1.e-100])**10 >>> j = np.seterr(invalid='raise') >>> np.sqrt(np.array([-1.])) FloatingPointError: invalid value encountered in sqrt >>> def errorhandler(errstr, errflag): ... print("saw stupid error!") >>> np.seterrcall(errorhandler) <function err_handler at 0x...> >>> j = np.seterr(all='call') >>> np.zeros(5, dtype=np.int32)/0 FloatingPointError: invalid value encountered in divide saw stupid error! >>> j = np.seterr(**oldsettings) # restore previous ... # error-handling settings Interfacing to C Only a survey of the choices. Little detail on how each works. Bare metal, wrap your own C-code manually. Plusses: Efficient No dependencies on other tools Minuses: Lots of learning overhead: need to learn basics of Python C API need to learn basics of numpy C API need to learn how to handle reference counting and love it. Reference counting often difficult to get right. getting it wrong leads to memory leaks, and worse, segfaults API will change for Python 3.0! Cython Plusses: avoid learning C API’s no dealing with reference counting can code in pseudo python and generate C code can also interface to existing C code should shield you from changes to Python C api has become the de-facto standard within the scientific Python community fast indexing support for arrays Minuses: Can write code in non-standard form which may become obsolete Not as flexible as manual wrapping ctypes Plusses: part of Python standard library good for interfacing to existing shareable libraries, particularly Windows DLLs avoids API/reference counting issues good numpy support: arrays have all these in their ctypes attribute: a.ctypes.data a.ctypes.data_as a.ctypes.shape a.ctypes.shape_as a.ctypes.strides a.ctypes.strides_as Minuses: can’t use for writing code to be turned into C extensions, only a wrapper tool. SWIG (automatic wrapper generator) Plusses: around a long time multiple scripting language support C++ support Good for wrapping large (many functions) existing C libraries Minuses: generates lots of code between Python and the C code can cause performance problems that are nearly impossible to optimize out interface files can be hard to write doesn’t necessarily avoid reference counting issues or needing to know API’s scipy.weave Plusses: can turn many numpy expressions into C code dynamic compiling and loading of generated C code can embed pure C code in Python module and have weave extract, generate interfaces and compile, etc. Minuses: Future very uncertain: it’s the only part of Scipy not ported to Python 3 and is effectively deprecated in favor of Cython. Psyco Plusses: Turns pure python into efficient machine code through jit-like optimizations very fast when it optimizes well Minuses: Only on intel (windows?) Doesn’t do much for numpy? Interfacing to Fortran: The clear choice to wrap Fortran code is f2py. Pyfort is an older alternative, but not supported any longer. Fwrap is a newer project that looked promising but isn’t being developed any longer. Interfacing to C++: Cython CXX Boost.python SWIG SIP (used mainly in PyQT)
numpy.user.misc
numpy.ndarray.__abs__ method ndarray.__abs__(self)
numpy.reference.generated.numpy.ndarray.__abs__
numpy.ndarray.__add__ method ndarray.__add__(value, /) Return self+value.
numpy.reference.generated.numpy.ndarray.__add__
numpy.ndarray.__and__ method ndarray.__and__(value, /) Return self&value.
numpy.reference.generated.numpy.ndarray.__and__
numpy.ndarray.__array__ method ndarray.__array__([dtype, ]/) → reference if type unchanged, copy otherwise. Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is different from the current dtype of the array.
numpy.reference.generated.numpy.ndarray.__array__
numpy.ndarray.__array_wrap__ method ndarray.__array_wrap__(array, [context, ]/) Returns a view of array with the same type as self.
numpy.reference.generated.numpy.ndarray.__array_wrap__
numpy.ndarray.__bool__ method ndarray.__bool__(/) self != 0
numpy.reference.generated.numpy.ndarray.__bool__
numpy.ndarray.__class_getitem__ method ndarray.__class_getitem__(item, /) Return a parametrized wrapper around the ndarray type. New in version 1.22. Returns aliastypes.GenericAlias A parametrized ndarray type. See also PEP 585 Type hinting generics in standard collections. numpy.typing.NDArray An ndarray alias generic w.r.t. its dtype.type. Notes This method is only available for python 3.9 and later. Examples >>> from typing import Any >>> import numpy as np >>> np.ndarray[Any, np.dtype[Any]] numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
numpy.reference.generated.numpy.ndarray.__class_getitem__
numpy.ndarray.__complex__ method ndarray.__complex__()
numpy.reference.generated.numpy.ndarray.__complex__
numpy.ndarray.__contains__ method ndarray.__contains__(key, /) Return key in self.
numpy.reference.generated.numpy.ndarray.__contains__
numpy.ndarray.__copy__ method ndarray.__copy__() Used if copy.copy is called on an array. Returns a copy of the array. Equivalent to a.copy(order='K').
numpy.reference.generated.numpy.ndarray.__copy__
numpy.ndarray.__deepcopy__ method ndarray.__deepcopy__(memo, /) → Deep copy of array. Used if copy.deepcopy is called on an array.
numpy.reference.generated.numpy.ndarray.__deepcopy__
numpy.ndarray.__divmod__ method ndarray.__divmod__(value, /) Return divmod(self, value).
numpy.reference.generated.numpy.ndarray.__divmod__
numpy.ndarray.__eq__ method ndarray.__eq__(value, /) Return self==value.
numpy.reference.generated.numpy.ndarray.__eq__
numpy.ndarray.__float__ method ndarray.__float__(self)
numpy.reference.generated.numpy.ndarray.__float__
numpy.ndarray.__floordiv__ method ndarray.__floordiv__(value, /) Return self//value.
numpy.reference.generated.numpy.ndarray.__floordiv__
numpy.ndarray.__ge__ method ndarray.__ge__(value, /) Return self>=value.
numpy.reference.generated.numpy.ndarray.__ge__
numpy.ndarray.__getitem__ method ndarray.__getitem__(key, /) Return self[key].
numpy.reference.generated.numpy.ndarray.__getitem__
numpy.ndarray.__gt__ method ndarray.__gt__(value, /) Return self>value.
numpy.reference.generated.numpy.ndarray.__gt__
numpy.ndarray.__iadd__ method ndarray.__iadd__(value, /) Return self+=value.
numpy.reference.generated.numpy.ndarray.__iadd__
numpy.ndarray.__iand__ method ndarray.__iand__(value, /) Return self&=value.
numpy.reference.generated.numpy.ndarray.__iand__
numpy.ndarray.__ifloordiv__ method ndarray.__ifloordiv__(value, /) Return self//=value.
numpy.reference.generated.numpy.ndarray.__ifloordiv__
numpy.ndarray.__ilshift__ method ndarray.__ilshift__(value, /) Return self<<=value.
numpy.reference.generated.numpy.ndarray.__ilshift__
numpy.ndarray.__imod__ method ndarray.__imod__(value, /) Return self%=value.
numpy.reference.generated.numpy.ndarray.__imod__
numpy.ndarray.__imul__ method ndarray.__imul__(value, /) Return self*=value.
numpy.reference.generated.numpy.ndarray.__imul__
numpy.ndarray.__int__ method ndarray.__int__(self)
numpy.reference.generated.numpy.ndarray.__int__
numpy.ndarray.__invert__ method ndarray.__invert__(/) ~self
numpy.reference.generated.numpy.ndarray.__invert__
numpy.ndarray.__ior__ method ndarray.__ior__(value, /) Return self|=value.
numpy.reference.generated.numpy.ndarray.__ior__
numpy.ndarray.__ipow__ method ndarray.__ipow__(value, /) Return self**=value.
numpy.reference.generated.numpy.ndarray.__ipow__
numpy.ndarray.__irshift__ method ndarray.__irshift__(value, /) Return self>>=value.
numpy.reference.generated.numpy.ndarray.__irshift__
numpy.ndarray.__isub__ method ndarray.__isub__(value, /) Return self-=value.
numpy.reference.generated.numpy.ndarray.__isub__
numpy.ndarray.__itruediv__ method ndarray.__itruediv__(value, /) Return self/=value.
numpy.reference.generated.numpy.ndarray.__itruediv__
numpy.ndarray.__ixor__ method ndarray.__ixor__(value, /) Return self^=value.
numpy.reference.generated.numpy.ndarray.__ixor__
numpy.ndarray.__le__ method ndarray.__le__(value, /) Return self<=value.
numpy.reference.generated.numpy.ndarray.__le__
numpy.ndarray.__len__ method ndarray.__len__(/) Return len(self).
numpy.reference.generated.numpy.ndarray.__len__
numpy.ndarray.__lshift__ method ndarray.__lshift__(value, /) Return self<<value.
numpy.reference.generated.numpy.ndarray.__lshift__
numpy.ndarray.__lt__ method ndarray.__lt__(value, /) Return self<value.
numpy.reference.generated.numpy.ndarray.__lt__
numpy.ndarray.__matmul__ method ndarray.__matmul__(value, /) Return self@value.
numpy.reference.generated.numpy.ndarray.__matmul__
numpy.ndarray.__mod__ method ndarray.__mod__(value, /) Return self%value.
numpy.reference.generated.numpy.ndarray.__mod__
numpy.ndarray.__mul__ method ndarray.__mul__(value, /) Return self*value.
numpy.reference.generated.numpy.ndarray.__mul__
numpy.ndarray.__ne__ method ndarray.__ne__(value, /) Return self!=value.
numpy.reference.generated.numpy.ndarray.__ne__
numpy.ndarray.__neg__ method ndarray.__neg__(/) -self
numpy.reference.generated.numpy.ndarray.__neg__
numpy.ndarray.__new__ method ndarray.__new__(*args, **kwargs)
numpy.reference.generated.numpy.ndarray.__new__
numpy.ndarray.__or__ method ndarray.__or__(value, /) Return self|value.
numpy.reference.generated.numpy.ndarray.__or__
numpy.ndarray.__pos__ method ndarray.__pos__(/) +self
numpy.reference.generated.numpy.ndarray.__pos__
numpy.ndarray.__pow__ method ndarray.__pow__(value, mod=None, /) Return pow(self, value, mod).
numpy.reference.generated.numpy.ndarray.__pow__
numpy.ndarray.__reduce__ method ndarray.__reduce__() For pickling.
numpy.reference.generated.numpy.ndarray.__reduce__
numpy.ndarray.__repr__ method ndarray.__repr__(/) Return repr(self).
numpy.reference.generated.numpy.ndarray.__repr__
numpy.ndarray.__rshift__ method ndarray.__rshift__(value, /) Return self>>value.
numpy.reference.generated.numpy.ndarray.__rshift__
numpy.ndarray.__setitem__ method ndarray.__setitem__(key, value, /) Set self[key] to value.
numpy.reference.generated.numpy.ndarray.__setitem__
numpy.ndarray.__setstate__ method ndarray.__setstate__(state, /) For unpickling. The state argument must be a sequence that contains the following elements: Parameters versionint optional pickle version. If omitted defaults to 0. shapetuple dtypedata-type isFortranbool rawdatastring or list a binary string with the data (or a list if ‘a’ is an object array)
numpy.reference.generated.numpy.ndarray.__setstate__
numpy.ndarray.__str__ method ndarray.__str__(/) Return str(self).
numpy.reference.generated.numpy.ndarray.__str__
numpy.ndarray.__sub__ method ndarray.__sub__(value, /) Return self-value.
numpy.reference.generated.numpy.ndarray.__sub__
numpy.ndarray.__truediv__ method ndarray.__truediv__(value, /) Return self/value.
numpy.reference.generated.numpy.ndarray.__truediv__
numpy.ndarray.__xor__ method ndarray.__xor__(value, /) Return self^value.
numpy.reference.generated.numpy.ndarray.__xor__
numpy.ndarray.all method ndarray.all(axis=None, out=None, keepdims=False, *, where=True) Returns True if all elements evaluate to True. Refer to numpy.all for full documentation. See also numpy.all equivalent function
numpy.reference.generated.numpy.ndarray.all
numpy.ndarray.any method ndarray.any(axis=None, out=None, keepdims=False, *, where=True) Returns True if any of the elements of a evaluate to True. Refer to numpy.any for full documentation. See also numpy.any equivalent function
numpy.reference.generated.numpy.ndarray.any
numpy.ndarray.argmax method ndarray.argmax(axis=None, out=None) Return indices of the maximum values along the given axis. Refer to numpy.argmax for full documentation. See also numpy.argmax equivalent function
numpy.reference.generated.numpy.ndarray.argmax
numpy.ndarray.argmin method ndarray.argmin(axis=None, out=None) Return indices of the minimum values along the given axis. Refer to numpy.argmin for detailed documentation. See also numpy.argmin equivalent function
numpy.reference.generated.numpy.ndarray.argmin
numpy.ndarray.argpartition method ndarray.argpartition(kth, axis=- 1, kind='introselect', order=None) Returns the indices that would partition this array. Refer to numpy.argpartition for full documentation. New in version 1.8.0. See also numpy.argpartition equivalent function
numpy.reference.generated.numpy.ndarray.argpartition
numpy.ndarray.argsort method ndarray.argsort(axis=- 1, kind=None, order=None) Returns the indices that would sort this array. Refer to numpy.argsort for full documentation. See also numpy.argsort equivalent function
numpy.reference.generated.numpy.ndarray.argsort
numpy.ndarray.astype method ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True) Copy of the array, cast to a specified type. Parameters dtypestr or dtype Typecode or data-type to which the array is cast. order{‘C’, ‘F’, ‘A’, ‘K’}, optional Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility. ‘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. subokbool, optional If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array. copybool, optional By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy. Returns arr_tndarray Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order. Raises ComplexWarning When casting from complex to float or int. To avoid this, one should use a.real.astype(t). Notes Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not. Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted. Examples >>> x = np.array([1, 2, 2.5]) >>> x array([1. , 2. , 2.5]) >>> x.astype(int) array([1, 2, 2])
numpy.reference.generated.numpy.ndarray.astype
numpy.ndarray.base attribute ndarray.base Base object if memory is from some other object. Examples The base of an array that owns its memory is None: >>> x = np.array([1,2,3,4]) >>> x.base is None True Slicing creates a view, whose memory is shared with x: >>> y = x[2:] >>> y.base is x True
numpy.reference.generated.numpy.ndarray.base
numpy.ndarray.byteswap method ndarray.byteswap(inplace=False) Swap the bytes of the array elements Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually. Parameters inplacebool, optional If True, swap bytes in-place, default is False. Returns outndarray The byteswapped array. If inplace is True, this is a view to self. Examples >>> A = np.array([1, 256, 8755], dtype=np.int16) >>> list(map(hex, A)) ['0x1', '0x100', '0x2233'] >>> A.byteswap(inplace=True) array([ 256, 1, 13090], dtype=int16) >>> list(map(hex, A)) ['0x100', '0x1', '0x3322'] Arrays of byte-strings are not swapped >>> A = np.array([b'ceg', b'fac']) >>> A.byteswap() array([b'ceg', b'fac'], dtype='|S3') A.newbyteorder().byteswap() produces an array with the same values but different representation in memory >>> A = np.array([1, 2, 3]) >>> A.view(np.uint8) array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0], dtype=uint8) >>> A.newbyteorder().byteswap(inplace=True) array([1, 2, 3]) >>> A.view(np.uint8) array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3], dtype=uint8)
numpy.reference.generated.numpy.ndarray.byteswap
numpy.ndarray.choose method ndarray.choose(choices, out=None, mode='raise') Use an index array to construct a new array from a set of choices. Refer to numpy.choose for full documentation. See also numpy.choose equivalent function
numpy.reference.generated.numpy.ndarray.choose
numpy.ndarray.clip method ndarray.clip(min=None, max=None, out=None, **kwargs) Return an array whose values are limited to [min, max]. One of max or min must be given. Refer to numpy.clip for full documentation. See also numpy.clip equivalent function
numpy.reference.generated.numpy.ndarray.clip
numpy.ndarray.compress method ndarray.compress(condition, axis=None, out=None) Return selected slices of this array along given axis. Refer to numpy.compress for full documentation. See also numpy.compress equivalent function
numpy.reference.generated.numpy.ndarray.compress
numpy.ndarray.conj method ndarray.conj() Complex-conjugate all elements. Refer to numpy.conjugate for full documentation. See also numpy.conjugate equivalent function
numpy.reference.generated.numpy.ndarray.conj
numpy.ndarray.conjugate method ndarray.conjugate() Return the complex conjugate, element-wise. Refer to numpy.conjugate for full documentation. See also numpy.conjugate equivalent function
numpy.reference.generated.numpy.ndarray.conjugate
numpy.ndarray.copy method ndarray.copy(order='C') Return a copy of the array. Parameters order{‘C’, ‘F’, ‘A’, ‘K’}, optional Controls the memory layout of the copy. ‘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. (Note that this function and numpy.copy are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.) See also numpy.copy Similar function with different default behavior numpy.copyto Notes This function is the preferred method for creating an array copy. The function numpy.copy is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default. Examples >>> x = np.array([[1,2,3],[4,5,6]], order='F') >>> y = x.copy() >>> x.fill(0) >>> x array([[0, 0, 0], [0, 0, 0]]) >>> y array([[1, 2, 3], [4, 5, 6]]) >>> y.flags['C_CONTIGUOUS'] True
numpy.reference.generated.numpy.ndarray.copy
numpy.ndarray.ctypes attribute ndarray.ctypes An object to simplify the interaction of the array with the ctypes module. This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library. Parameters None Returns cPython object Possessing attributes data, shape, strides, etc. See also numpy.ctypeslib Notes Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes, as well as documented private attributes): _ctypes.data A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as self._array_interface_['data'][0]. Note that unlike data_as, a reference will not be kept to the array: code like ctypes.c_void_p((a + b).ctypes.data) will result in a pointer to a deallocated array, and should be spelt (a + b).ctypes.data_as(ctypes.c_void_p) _ctypes.shape (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform (see c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array. _ctypes.strides (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array. _ctypes.data_as(obj)[source] Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)). The returned pointer will keep a reference to the array. _ctypes.shape_as(obj)[source] Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short). _ctypes.strides_as(obj)[source] Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong). If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as_parameter attribute which will return an integer equal to the data attribute. Examples >>> import ctypes >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32) >>> x array([[0, 1], [2, 3]], dtype=int32) >>> x.ctypes.data 31962608 # may vary >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)) <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents c_uint(0) >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents c_ulong(4294967296) >>> x.ctypes.shape <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary >>> x.ctypes.strides <numpy.core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
numpy.reference.generated.numpy.ndarray.ctypes
numpy.ndarray.cumprod method ndarray.cumprod(axis=None, dtype=None, out=None) Return the cumulative product of the elements along the given axis. Refer to numpy.cumprod for full documentation. See also numpy.cumprod equivalent function
numpy.reference.generated.numpy.ndarray.cumprod
numpy.ndarray.cumsum method ndarray.cumsum(axis=None, dtype=None, out=None) Return the cumulative sum of the elements along the given axis. Refer to numpy.cumsum for full documentation. See also numpy.cumsum equivalent function
numpy.reference.generated.numpy.ndarray.cumsum
numpy.ndarray.data attribute ndarray.data Python buffer object pointing to the start of the array’s data.
numpy.reference.generated.numpy.ndarray.data
numpy.ndarray.diagonal method ndarray.diagonal(offset=0, axis1=0, axis2=1) Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed. Refer to numpy.diagonal for full documentation. See also numpy.diagonal equivalent function
numpy.reference.generated.numpy.ndarray.diagonal
numpy.ndarray.dtype attribute ndarray.dtype Data-type of the array’s elements. Parameters None Returns dnumpy dtype object See also numpy.dtype Examples >>> x array([[0, 1], [2, 3]]) >>> x.dtype dtype('int32') >>> type(x.dtype) <type 'numpy.dtype'>
numpy.reference.generated.numpy.ndarray.dtype
numpy.ndarray.dump method ndarray.dump(file) Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load. Parameters filestr or Path A string naming the dump file. Changed in version 1.17.0: pathlib.Path objects are now accepted.
numpy.reference.generated.numpy.ndarray.dump
numpy.ndarray.dumps method ndarray.dumps() Returns the pickle of the array as a string. pickle.loads will convert the string back to an array. Parameters None
numpy.reference.generated.numpy.ndarray.dumps
numpy.ndarray.fill method ndarray.fill(value) Fill the array with a scalar value. Parameters valuescalar All elements of a will be assigned this value. Examples >>> a = np.array([1, 2]) >>> a.fill(0) >>> a array([0, 0]) >>> a = np.empty(2) >>> a.fill(1) >>> a array([1., 1.])
numpy.reference.generated.numpy.ndarray.fill
numpy.ndarray.flags attribute ndarray.flags Information about the memory layout of the array. Notes The flags object can be accessed dictionary-like (as in a.flags['WRITEABLE']), or by using lowercased attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access. Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags. The array flags cannot be set arbitrarily: UPDATEIFCOPY can only be set False. WRITEBACKIFCOPY can only be set False. ALIGNED can only be set True if the data is truly aligned. WRITEABLE can only be set True if the array owns its own memory or the ultimate owner of the memory exposes a writeable buffer interface or is a string. Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays. Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0] == self.itemsize for Fortran-style contiguous arrays is true. Attributes C_CONTIGUOUS (C) The data is in a single, C-style contiguous segment. F_CONTIGUOUS (F) The data is in a single, Fortran-style contiguous segment. OWNDATA (O) The array owns the memory it uses or borrows it from another object. WRITEABLE (W) The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception. ALIGNED (A) The data and all elements are aligned appropriately for the hardware. WRITEBACKIFCOPY (X) This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array. UPDATEIFCOPY (U) (Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array. FNC F_CONTIGUOUS and not C_CONTIGUOUS. FORC F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). BEHAVED (B) ALIGNED and WRITEABLE. CARRAY (CA) BEHAVED and C_CONTIGUOUS. FARRAY (FA) BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
numpy.reference.generated.numpy.ndarray.flags
numpy.ndarray.flat attribute ndarray.flat A 1-D iterator over the array. This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object. See also flatten Return a copy of the array collapsed into one dimension. flatiter Examples >>> x = np.arange(1, 7).reshape(2, 3) >>> x array([[1, 2, 3], [4, 5, 6]]) >>> x.flat[3] 4 >>> x.T array([[1, 4], [2, 5], [3, 6]]) >>> x.T.flat[3] 5 >>> type(x.flat) <class 'numpy.flatiter'> An assignment example: >>> x.flat = 3; x array([[3, 3, 3], [3, 3, 3]]) >>> x.flat[[1,4]] = 1; x array([[3, 1, 3], [3, 1, 3]])
numpy.reference.generated.numpy.ndarray.flat
numpy.ndarray.flatten method ndarray.flatten(order='C') Return a copy of the array collapsed into one dimension. Parameters order{‘C’, ‘F’, ‘A’, ‘K’}, optional ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’. Returns yndarray A copy of the input array, flattened to one dimension. See also ravel Return a flattened array. flat A 1-D flat iterator over the array. Examples >>> a = np.array([[1,2], [3,4]]) >>> a.flatten() array([1, 2, 3, 4]) >>> a.flatten('F') array([1, 3, 2, 4])
numpy.reference.generated.numpy.ndarray.flatten
numpy.ndarray.getfield method ndarray.getfield(dtype, offset=0) Returns a field of the given array as a certain type. A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes. Parameters dtypestr or dtype The data type of the view. The dtype size of the view can not be larger than that of the array itself. offsetint Number of bytes to skip before beginning the element view. Examples >>> x = np.diag([1.+1.j]*2) >>> x[1, 1] = 2 + 4.j >>> x array([[1.+1.j, 0.+0.j], [0.+0.j, 2.+4.j]]) >>> x.getfield(np.float64) array([[1., 0.], [0., 2.]]) By choosing an offset of 8 bytes we can select the complex part of the array for our view: >>> x.getfield(np.float64, offset=8) array([[1., 0.], [0., 4.]])
numpy.reference.generated.numpy.ndarray.getfield
numpy.ndarray.imag attribute ndarray.imag The imaginary part of the array. Examples >>> x = np.sqrt([1+0j, 0+1j]) >>> x.imag array([ 0. , 0.70710678]) >>> x.imag.dtype dtype('float64')
numpy.reference.generated.numpy.ndarray.imag
numpy.ndarray.item method ndarray.item(*args) Copy an element of an array to a standard Python scalar and return it. Parameters *argsArguments (variable number and type) none: in this case, the method only works for arrays with one element (a.size == 1), which element is copied into a standard Python scalar object and returned. int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return. tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array. Returns zStandard Python scalar object A copy of the specified element of the array as a suitable Python scalar Notes When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned. item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math. Examples >>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.item(3) 1 >>> x.item(7) 0 >>> x.item((0, 1)) 2 >>> x.item((2, 2)) 1
numpy.reference.generated.numpy.ndarray.item
numpy.ndarray.itemset method ndarray.itemset(*args) Insert scalar into an array (scalar is cast to array’s dtype, if possible) There must be at least 1 argument, and define the last argument as item. Then, a.itemset(*args) is equivalent to but faster than a[args] = item. The item should be a scalar value and args must select a single item in the array a. Parameters *argsArguments If one argument: a scalar, only used in case a is of size 1. If two arguments: the last argument is the value to be set and must be a scalar, the first argument specifies a single array element location. It is either an int or a tuple. Notes Compared to indexing syntax, itemset provides some speed increase for placing a scalar into a particular location in an ndarray, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when using itemset (and item) inside a loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration. Examples >>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.itemset(4, 0) >>> x.itemset((2, 2), 9) >>> x array([[2, 2, 6], [1, 0, 6], [1, 0, 9]])
numpy.reference.generated.numpy.ndarray.itemset
numpy.ndarray.itemsize attribute ndarray.itemsize Length of one array element in bytes. Examples >>> x = np.array([1,2,3], dtype=np.float64) >>> x.itemsize 8 >>> x = np.array([1,2,3], dtype=np.complex128) >>> x.itemsize 16
numpy.reference.generated.numpy.ndarray.itemsize
numpy.ndarray.max method ndarray.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True) Return the maximum along a given axis. Refer to numpy.amax for full documentation. See also numpy.amax equivalent function
numpy.reference.generated.numpy.ndarray.max