pydoc > numpy

๐Ÿ“ฆ Help on package numpy:

๐Ÿ“– NAME

๐Ÿ numpy

๐Ÿ“– DESCRIPTION

NumPy


Provides

  1. ๐Ÿ“ฆ An array object of arbitrary homogeneous items
  2. โšก Fast mathematical operations over arrays
  3. ๐Ÿงฎ Linear Algebra, Fourier Transforms, Random Number Generation

๐Ÿ“š How to use the documentation

Documentation is available in two forms: docstrings provided with the code, and a loose standing reference guide, available from the NumPy homepage.

We recommend exploring the docstrings using IPython, an advanced Python shell with TAB-completion and introspection capabilities. See below for further instructions.

The docstring examples assume that numpy has been imported as np:

>>> import numpy as np

Code snippets are indicated by three greater-than signs:

>>> x = 42
>>> x = x + 1

Use the built-in help function to view a function's docstring:

>>> help(np.sort)
... # doctest: +SKIP

For some objects, np.info(obj) may provide additional help. This is particularly true if you see the line "Help on ufunc object:" at the top of the help() page. Ufuncs are implemented in C, not Python, for speed. The native Python help() does not know how to view their help, but our np.info() function does.

To search for documents containing a keyword, do:

>>> np.lookfor('keyword')
... # doctest: +SKIP

General-purpose documents like a glossary and help on the basic concepts of numpy are available under the doc sub-module:

>>> from numpy import doc
>>> help(doc)
... # doctest: +SKIP

๐Ÿ“ฆ Available subpackages

๐Ÿ”ง Utilities

๐Ÿ’ป Viewing documentation using IPython

Start IPython with the NumPy profile (ipython -p numpy), which will import numpy under the alias np. Then, use the cpaste command to paste examples into the shell. To see which functions are available in numpy, type np.<TAB> (where <TAB> refers to the TAB key), or use np.*cos*?<ENTER> (where <ENTER> refers to the ENTER key) to narrow down the list. To view the docstring for a function, use np.cos?<ENTER> (to view the docstring) and np.cos??<ENTER> (to view the source code).

๐Ÿ“ Copies vs. in-place operation

Most of the functions in numpy return a copy of the array argument (e.g., np.sort). In-place versions of these functions are often available as array methods, i.e. x = np.array([1,2,3]); x.sort(). Exceptions to this rule are documented.

๐Ÿ“ฆ PACKAGE CONTENTS

๐Ÿ“ฆ Submodules

๐Ÿ“ฆ CLASSES

๐Ÿ”— Class hierarchy:
    builtins.DeprecationWarning(builtins.Warning)
        ModuleDeprecationWarning
    builtins.IndexError(builtins.LookupError)
        AxisError(builtins.ValueError, builtins.IndexError)
    builtins.RuntimeError(builtins.Exception)
        TooHardError
    builtins.RuntimeWarning(builtins.Warning)
        ComplexWarning
    builtins.UserWarning(builtins.Warning)
        RankWarning
        VisibleDeprecationWarning
    builtins.ValueError(builtins.Exception)
        AxisError(builtins.ValueError, builtins.IndexError)
    builtins.bytes(builtins.object)
        bytes_(builtins.bytes, character)
    builtins.object
        DataSource
        MachAr
        broadcast
        busdaycalendar
        dtype
        finfo
        flatiter
        format_parser
        generic
            bool_
            datetime64
            flexible
                character
                    bytes_(builtins.bytes, character)
                    str_(builtins.str, character)
                void
                    record
            number
                inexact
                    complexfloating
                        complex128(complexfloating, builtins.complex)
                        complex256
                        complex64
                    floating
                        float128
                        float16
                        float32
                        float64(floating, builtins.float)
                integer
                    signedinteger
                        int16
                        int32
                        int64
                        int8
                        longlong
                        timedelta64
                    unsignedinteger
                        uint16
                        uint32
                        uint64
                        uint8
                        ulonglong
            object_
        iinfo
        ndarray
            chararray
            matrix
            memmap
            recarray
        ndenumerate
        ndindex
        nditer
        poly1d
        ufunc
        vectorize
    builtins.str(builtins.object)
        str_(builtins.str, character)
    contextlib.ContextDecorator(builtins.object)
        errstate

โš ๏ธ AxisError

Raised when an axis supplied is invalid.

Data descriptors:

Inherited from builtins.ValueError:

Inherited from builtins.BaseException:

โš ๏ธ ComplexWarning

Warning raised when casting a complex dtype to a real dtype.

Inherited from builtins.RuntimeWarning:

Inherited from builtins.BaseException: (same as above)

๐Ÿ“‚ DataSource

Generic data source file (file, http, ftp, โ€ฆ).

Data descriptors:

โš™๏ธ MachAr

Diagnosing machine parameters for floating point numbers.

Data descriptors:

Attributes: ibeta, it, machep, eps, negep, epsneg, iexp, minexp, xmin, maxexp, xmax, irnd, ngrd, epsilon, tiny, huge, precision, resolution.

โš ๏ธ ModuleDeprecationWarning

Special deprecation warning that does not cause test failures in nose.

Inherited from builtins.DeprecationWarning:

Inherited from builtins.BaseException: (same as above)

โš ๏ธ RankWarning

Issued by polyfit when the Vandermonde matrix is rank deficient.

Inherited from builtins.UserWarning:

Inherited from builtins.BaseException: (same as above)

โŒ TooHardError

Runtime error.

Inherited from builtins.RuntimeError:

Inherited from builtins.BaseException: (same as above)

โš ๏ธ VisibleDeprecationWarning

Visible deprecation warning for user bugs.

Inherited from builtins.UserWarning:

Inherited from builtins.BaseException: (same as above)

๐Ÿ”  bool_ (numpy.bool8)

Boolean type stored as a byte. Character code: '?'

Inherited from generic: Many methods for arithmetic, array operations, scalar attributes (see full list in original).

Data descriptors inherited from generic:

๐Ÿ”ง broadcast

Produce an object that mimics broadcasting.

Data descriptors:

๐Ÿ“… busdaycalendar

Business day calendar object for the busday family of functions.

Data descriptors:

๐Ÿ”ข int8 (numpy.byte)

Signed integer type, compatible with C char. Character code: 'b'

Inherited from integer: __round__, denominator, numerator.

Inherited from generic: (same as bool_ above)

๐Ÿ”ค bytes_ (numpy.string_)

Byte string type, strips trailing null bytes in arrays. Character code: 'S'

Inherited from builtins.bytes: All standard bytes methods (capitalize, center, count, decode, endswith, expandtabs, find, hex, index, isalnum, isalpha, isascii, isdigit, islower, isspace, istitle, isupper, join, ljust, lower, lstrip, partition, removeprefix, removesuffix, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill, fromhex, maketrans)

Inherited from generic: (same as above)

๐Ÿ”ข int types (int8, int16, int32, int64, uint8, uint16, uint32, uint64, longlong, ulonglong, etc.)

All integer scalar types share the same methods and attributes as int8. They differ in range and character code. See int8 for complete method list.

๐Ÿ”ข float types (float16, float32, float64, float128, complex64, complex128, complex256)

Floating-point and complex scalar types. They inherit from floating or complexfloating. Methods include arithmetic operations, __float__, __int__, and all generic methods. Data descriptors include real, imag, etc.

๐Ÿ”  str_ (numpy.str_)

String type. Character code 'U'. Similar to bytes_ but for Unicode strings. Inherits from builtins.str and character.

๐Ÿ“ฆ generic

Base class for all NumPy scalar types. Provides the core methods and descriptors listed above for bool_.

๐Ÿ“ฆ flexible, character, void, record

Subclasses of generic for structured and character types.

๐Ÿ”ข number, integer, signedinteger, unsignedinteger, inexact, floating, complexfloating

Intermediate abstract base classes for numeric types.

๐Ÿ“ฆ object_

Scalar type for Python objects.

๐Ÿ“ฆ datetime64, timedelta64

Date and time scalar types.

๐Ÿ“ฆ dtype, finfo, iinfo, flatiter, format_parser, ndarray, chararray, matrix, memmap, recarray, ndenumerate, ndindex, nditer, poly1d, ufunc, vectorize, errstate

Additional NumPy classes not detailed here. See full documentation for details.

๐Ÿงฌ CLASSES

๐Ÿ“ฆ class bytes(builtins.bytes)

bytes(iterable_of_ints) โ†’ bytes
bytes(string, encoding[, errors]) โ†’ bytes
bytes(bytes_or_buffer) โ†’ immutable copy of bytes_or_buffer
bytes(int) โ†’ bytes object of size given by the parameter initialized with null bytes
bytes() โ†’ empty bytes object

Construct an immutable array of bytes.

๐Ÿ”ง Methods defined here:

๐Ÿ”ง Class methods inherited from builtins.bytes:

๐Ÿ”ง Static methods inherited from builtins.bytes:

๐Ÿ“‚ Methods inherited from generic:

๐Ÿ“Š Data descriptors inherited from generic:


๐Ÿงช class complex128(complexfloating, builtins.complex)

cdouble(real=0, imag=0)

Complex number type composed of two double-precision floating-point numbers, compatible with Python complex.

Method resolution order:

๐Ÿ”ง Methods defined here:

๐Ÿ”ง Static methods defined here:

๐Ÿ“‚ Methods inherited from complexfloating:

๐Ÿ“‚ Methods inherited from generic:

๐Ÿ“Š Data descriptors inherited from generic:

๐Ÿ“‚ Methods inherited from builtins.complex:


๐Ÿงช class complex128 (alias: cfloat)

Identical to cdouble (complex128) above. See the cdouble class documentation for all details.


๐Ÿ”ค class character(flexible)

Abstract base class of all character string scalar types.

Method resolution order:

๐Ÿ“‚ Methods inherited from generic:

๐Ÿ“Š Data descriptors inherited from generic:

Data and other attributes inherited from generic:


๐Ÿ“ class chararray(ndarray)

chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C')

Provides a convenient view on arrays of string and unicode values.

Note: The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations.

Versus a regular NumPy array of type str or unicode, this class adds the following functionality:

  1. values automatically have whitespace removed from the end when indexed
  2. comparison operators automatically remove whitespace from the end when comparing values
  3. vectorized string operations are provided as methods (e.g. .endswith) and infix operators (e.g. "+", "*", "%")

chararrays should be created using numpy.char.array or numpy.char.asarray, rather than this constructor directly.

This constructor creates the array, using buffer (with offset and strides) if it is not None. If buffer is None, then constructs a new array with strides in "C order", unless both len(shape) >= 2 and order='F', in which case strides is in "Fortran order".

๐Ÿ“‹ Methods

๐Ÿ“ฅ Parameters

๐Ÿ’ก Examples

>>> charar = np.chararray((3, 3))
>>> charar[:] = 'a'
>>> charar
chararray([[b'a', b'a', b'a'],
           [b'a', b'a', b'a'],
           [b'a', b'a', b'a']], dtype='|S1')

>>> charar = np.chararray(charar.shape, itemsize=5)
>>> charar[:] = 'abc'
>>> charar
chararray([[b'abc', b'abc', b'abc'],
           [b'abc', b'abc', b'abc'],
           [b'abc', b'abc', b'abc']], dtype='|S5')

Method resolution order:

๐Ÿ”ง Methods defined here:

๐Ÿ”ง Static methods defined here:

๐Ÿ“Š Data descriptors defined here:

Data and other attributes defined here:

๐Ÿ“‚ Methods inherited from ndarray:


๐Ÿ“ฆ CLASSES

๐Ÿ“˜ ndarray

๐Ÿ”ง view()

๐Ÿ“ Notes:

a.view() is used two different ways:

For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (e.g., converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of 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')])

๐Ÿ“„ Data descriptors inherited from ndarray:


๐Ÿ“˜ clongdouble = class complex256(complexfloating)

Complex number type composed of two extended-precision floating-point numbers.

Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.clongfloat
Alias: numpy.longcomplex
Alias on this platform (Linux x86_64): numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.

Method resolution order:

๐Ÿ”ง Methods defined here:

๐Ÿ”ง Static methods defined here:

๐Ÿ“š Methods inherited from complexfloating:

๐Ÿ“š Methods inherited from generic:

๐Ÿ“„ Data descriptors inherited from generic:


๐Ÿ“˜ clongfloat = class complex256(complexfloating)

Identical to clongdouble (alias). Methods and data descriptors are the same as those listed for clongdouble above.


๐Ÿ“˜ complex128 (complexfloating, builtins.complex)

Complex number type composed of two double-precision floating-point numbers, compatible with Python complex.

Character code: 'D'
Canonical name: numpy.cdouble
Alias: numpy.cfloat
Alias: numpy.complex_
Alias on this platform (Linux x86_64): numpy.complex128: Complex number type composed of 2 64-bit-precision floating-point numbers.

Method resolution order:

๐Ÿ”ง Methods defined here:

๐Ÿ”ง Static methods defined here:

๐Ÿ“š Methods inherited from complexfloating:

๐Ÿ“š Methods inherited from generic:

๐Ÿ“„ Data descriptors inherited from generic:

๐Ÿ“š Methods inherited from builtins.complex:


๐Ÿ“˜ complex256 (complexfloating)

Complex number type composed of two extended-precision floating-point numbers.

Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.clongfloat
Alias: numpy.longcomplex
Alias on this platform (Linux x86_64): numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.

Method resolution order:

Methods and data descriptors are identical to those of clongdouble (see above).


๐Ÿ“˜ complex64 (complexfloating)

Complex number type composed of two single-precision floating-point numbers.

Character code: 'F'
Canonical name: numpy.csingle
Alias: numpy.singlecomplex
Alias on this platform (Linux x86_64): numpy.complex64: Complex number type composed of 2 32-bit-precision floating-point numbers.

Method resolution order:

๐Ÿ”ง Methods defined here:

๐Ÿ”ง Static methods defined here:

๐Ÿ“š Methods inherited from complexfloating:

๐Ÿ“š Methods inherited from generic:

๐Ÿ“„ Data descriptors inherited from generic:


๐Ÿ“˜ complex_ = class complex128(complexfloating, builtins.complex)

Identical to complex128 (alias). Methods and data descriptors are the same as those listed for complex128 above.


๐Ÿ“˜ complexfloating (inexact)

Abstract base class of all complex number scalar types that are made up of floating-point numbers.

Method resolution order:

๐Ÿ”ง Methods defined here:

๐Ÿ“š Methods inherited from generic:

๐Ÿ“„ Data descriptors inherited from generic:

๐Ÿ“„ Data and other attributes inherited from generic:


๐Ÿ“˜ csingle = class complex64(complexfloating)

Identical to complex64 (alias). Methods and data descriptors are the same as those listed for complex64 above.


๐Ÿ“š CLASSES

๐Ÿ”ง class complexfloating

Methods inherited from complexfloating:

Methods inherited from generic:

Data descriptors inherited from generic:

๐Ÿ“… class datetime64(generic)

If created from a 64โ€‘bit integer, it represents an offset from 1970-01-01T00:00:00. If created from string, the string can be in ISO 8601 date or datetime format.

>>> np.datetime64(10, 'Y')
numpy.datetime64('1980')
>>> np.datetime64('1980', 'Y')
numpy.datetime64('1980')
>>> np.datetime64(10, 'D')
numpy.datetime64('1970-01-11')

See arrays.datetime for more information. Character code: 'M'

Method resolution order: datetime64, generic, builtins.object

Methods defined here:

Static methods:

Methods inherited from generic:

Data descriptors inherited from generic:

๐Ÿ”ข class float64 (double)

Doubleโ€‘precision floatingโ€‘point number type, compatible with Python float and C double. Character code: 'd'. Canonical name: numpy.double. 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.

Method resolution order: float64, floating, inexact, number, generic, builtins.float, builtins.object

Methods defined here:

Static methods:

Methods inherited from floating:

Methods inherited from generic:

Data descriptors inherited from generic:

Methods inherited from builtins.float:

Class methods inherited from builtins.float:

๐Ÿท๏ธ class dtype(builtins.object)

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:

See also: result_type

Examples:

>>> np.dtype(np.int16)
dtype('int16')

>>> np.dtype([('f1', np.int16)])
dtype([('f1', '<i2')])

>>> np.dtype([('f1', [('f1', np.int16)])])
dtype([('f1', [('f1', '<i2')])])

>>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
dtype([('f1', '<u8'), ('f2', '<i4')])

>>> np.dtype([('a','f8'),('b','S10')])
dtype([('a', '<f8'), ('b', 'S10')])

>>> np.dtype("i4, (2,3)f8")
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])

>>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
dtype([('hello', '<i8', (3,)), ('world', 'V10')])

>>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))

>>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
dtype([('gender', 'S1'), ('age', 'u1')])

>>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
dtype([('surname', 'S25'), ('age', 'u1')])

Methods defined here:

Static methods:

Data descriptors defined here:

โš ๏ธ class errstate(contextlib.ContextDecorator)

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.

Parameters (kwargs): divide, over, under, invalid โ€” each with values: 'ignore', 'warn', 'raise', 'call', 'print', 'log'.

See also: seterr, geterr, seterrcall, geterrcall

Methods defined here:

Methods inherited from contextlib.ContextDecorator:

Data descriptors inherited from contextlib.ContextDecorator:

๐Ÿ”ฌ class finfo(builtins.object)

Machine limits for floating point types.

Attributes:

Parameters: dtype (float, dtype, or instance) โ€” Kind of floating point dataโ€‘type about which to get information.

See also: MachAr, iinfo, spacing, nextafter

Methods defined here:

Static methods:

Data descriptors:

๐Ÿ”„ class flatiter(builtins.object)

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.

Methods defined here:

Data descriptors:

Other attributes: __hash__ = None

๐Ÿงฉ class flexible(generic)

Abstract base class of all scalar types without predefined length. The actual size of these types depends on the specific np.dtype instantiation.

Methods inherited from generic:

Data descriptors inherited from generic:

Other attributes: __hash__ = None

๐Ÿ”ข class float128(floating)

Extendedโ€‘precision floatingโ€‘point number type, compatible with C long double but not necessarily with IEEE 754 quadrupleโ€‘precision. Character code: 'g'. Canonical name: numpy.longdouble. Alias: numpy.longfloat. Alias on this platform (Linux x86_64): numpy.float128: 128โ€‘bit extendedโ€‘precision floatingโ€‘point number type.

Methods defined here:

Static methods: __new__(*args, **kwargs)

Methods inherited from floating: __round__(...)

Methods inherited from generic (same as float64 above): see the generic method list for details.

Data descriptors inherited from generic (same as float64): see above.

๐Ÿ”ข class float16(floating)

Halfโ€‘precision floatingโ€‘point number type. Character code: 'e'. Canonical name: numpy.half. Alias on this platform: numpy.float16: 16โ€‘bitโ€‘precision floatingโ€‘point number type: sign bit, 5 bits exponent, 10 bits mantissa.

Methods defined here:

Static methods: __new__(*args, **kwargs)

Methods inherited from floating: __round__(...)

Methods inherited from generic (same as float64): see above.

Data descriptors inherited from generic (same as float64): see above.

๐Ÿ”ข class float32(floating)

Singleโ€‘precision floatingโ€‘point number type, compatible with C float. Character code: 'f'. Canonical name: numpy.single. Alias on this platform: numpy.float32: 32โ€‘bitโ€‘precision floatingโ€‘point number type: sign bit, 8 bits exponent, 23 bits mantissa.

Methods defined here:

Static methods: __new__(*args, **kwargs)

Methods inherited from floating: __round__(...)

Methods inherited from generic (same as float64): see above.

Data descriptors inherited from generic (same as float64): see above.

Note: For brevity, the full list of inherited generic methods and data descriptors for float128, float16, and float32 have been omitted. They are identical to those listed for float64 and complexfloating.

๐Ÿ›๏ธ CLASSES

๐Ÿ“ See help(type) for accurate signature.


๐Ÿ”„ Methods inherited from floating:


๐Ÿ”„ Methods inherited from generic:


๐Ÿ“‹ Data descriptors inherited from generic:


๐Ÿงฌ class float64(floating, builtins.float)

float64(x=0, /) โ€” Double-precision floating-point number type, compatible with Python float and C double.

๐Ÿ“‹ Method resolution order: float64, floating, inexact, number, generic, builtins.float, builtins.object

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ”„ Methods inherited from floating:

๐Ÿ”„ Methods inherited from generic:

๐Ÿ“‹ Data descriptors inherited from generic:

๐Ÿ”„ Methods inherited from builtins.float:

โš™๏ธ Class methods inherited from builtins.float:


๐Ÿงฌ class floating(inexact)

Abstract base class of all floating-point scalar types.

๐Ÿ“‹ Method resolution order: floating, inexact, number, generic, builtins.object

๐Ÿ”ง Methods defined here:

๐Ÿ”„ Methods inherited from generic:

๐Ÿ“‹ Data descriptors inherited from generic:

๐Ÿ“ฆ Data and other attributes inherited from generic:


๐Ÿงฌ class format_parser(builtins.object)

format_parser(formats, names, titles, aligned=False, byteorder=None) โ€” 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

๐Ÿ“‹ Attributes:

๐Ÿ“ฅ Parameters:

๐Ÿ‘๏ธ 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')])

>>> 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')])

๐Ÿ”ง Methods defined here:

๐Ÿ“‹ Data descriptors defined here:


๐Ÿงฌ class generic(builtins.object)

Base class for numpy scalar types. Class from which most (all?) numpy scalar types are derived. Exposes the same API as ndarray.

๐Ÿ”ง Methods defined here:

๐Ÿ“‹ Data descriptors defined here:

๐Ÿ“ฆ Data and other attributes defined here:


๐Ÿงฌ half = class float16(floating)

Half-precision floating-point number type.

๐Ÿ“‹ Method resolution order: float16, floating, inexact, number, generic, builtins.object

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ”„ Methods inherited from floating:

๐Ÿ”„ Methods inherited from generic:

๐Ÿ“‹ Data descriptors inherited from generic:


๐Ÿงฌ class iinfo(builtins.object)

iinfo(int_type) โ€” Machine limits for integer types.

๐Ÿ“‹ Attributes:

๐Ÿ“ฅ Parameters:

๐Ÿ‘๏ธ See Also:

finfo โ€” The equivalent for floating point data types.

๐Ÿ“ Examples:

>>> ii16 = np.iinfo(np.int16)
>>> ii16.min
-32768
>>> ii16.max
32767
>>> ii32 = np.iinfo(np.int32)
>>> ii32.min
-2147483648
>>> ii32.max
2147483647

>>> ii32 = np.iinfo(np.int32(10))
>>> ii32.min
-2147483648
>>> ii32.max
2147483647

๐Ÿ”ง Methods defined here:

๐Ÿ”’ Readonly properties defined here:

๐Ÿ“‹ Data descriptors defined here:


๐Ÿงฌ class inexact(number)

Abstract base class of all numeric scalar types with a (potentially) inexact representation of the values in its range, such as floating-point numbers.

๐Ÿ“‹ Method resolution order: inexact, number, generic, builtins.object

๐Ÿ”„ Methods inherited from generic:

๐Ÿ“‹ Data descriptors inherited from generic:

๐Ÿ“ฆ Data and other attributes inherited from generic:


๐Ÿงฌ int0 = class int64(signedinteger)

Signed integer type, compatible with Python int and C long.

๐Ÿ“‹ Method resolution order: int64, signedinteger, integer, number, generic, builtins.object

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ”„ Methods inherited from integer:

๐Ÿ“‹ Data descriptors inherited from integer:

๐Ÿ”„ Methods inherited from generic:

๐Ÿ“‹ Data descriptors inherited from generic:


๐Ÿ“ Note: The above condenses repeated inherited method lists by referencing the base class. Full descriptions are available in the class generic definition.

๐Ÿ“š CLASSES

class int8(signedinteger)

๐Ÿ“ Signed integer type, compatible with C char.

๐Ÿ“ Method resolution order:

๐Ÿ› ๏ธ Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from integer:

๐Ÿ“Š Data descriptors inherited from integer:

๐Ÿ“‚ Methods inherited from generic:

๐Ÿ“‹ Data descriptors inherited from generic:


class int16(signedinteger)

๐Ÿ“ Signed integer type, compatible with C short.

๐Ÿ“ Method resolution order: int16, signedinteger, integer, number, generic, builtins.object

๐Ÿ› ๏ธ Methods defined here: same as int8 (operator methods, static __new__).

๐Ÿ” Methods inherited from integer: __round__

๐Ÿ“Š Data descriptors inherited from integer: denominator, numerator

๐Ÿ“‚ Methods inherited from generic: same as listed for int8 (including newbyteorder, etc.)

๐Ÿ“‹ Data descriptors inherited from generic: same as int8.


class int32(signedinteger)

๐Ÿ“ Signed integer type, compatible with C int.

๐Ÿ“ Method resolution order: int32, signedinteger, integer, number, generic, builtins.object

๐Ÿ› ๏ธ Methods defined here: same as int8.

๐Ÿ” Inherited from integer: __round__

๐Ÿ“Š Data descriptors from integer: denominator, numerator

๐Ÿ“‚ Methods inherited from generic: same as int8.

๐Ÿ“‹ Data descriptors inherited from generic: same as int8.


class int64(signedinteger)

๐Ÿ“ Signed integer type, compatible with Python int and C long.

๐Ÿ“ Method resolution order: int64, signedinteger, integer, number, generic, builtins.object

๐Ÿ› ๏ธ Methods defined here: same as int8 (plus all operator methods).

๐Ÿ” Inherited from integer: __round__

๐Ÿ“Š Data descriptors from integer: denominator, numerator

๐Ÿ“‚ Methods inherited from generic: same as int8.

๐Ÿ“‹ Data descriptors inherited from generic: same as int8.


class integer(number)

๐Ÿ“ Abstract base class of all integer scalar types.

๐Ÿ“ Method resolution order: integer, number, generic, builtins.object

๐Ÿ› ๏ธ Methods defined here:

๐Ÿ“Š Data descriptors defined here:

๐Ÿ“‚ Methods inherited from generic: same as int8 (including all operator methods, scalar methods, newbyteorder, etc.).

๐Ÿ“‹ Data descriptors inherited from generic: same as int8.

๐Ÿ“Œ Note: __hash__ = None (data and other attributes inherited from generic).


int_ = class int64 (signedinteger)

๐Ÿ“ Alias for int64. Same description, MRO, methods, and descriptors as int64.


intc = class int32 (signedinteger)

๐Ÿ“ Alias for int32. Same as int32.


intp = class int64 (signedinteger)

๐Ÿ“ Alias for int64. Same as int64.


longcomplex = class complex256(complexfloating)

๐Ÿ“ Complex number type composed of two extended-precision floating-point numbers.

๐Ÿ“ Method resolution order: complex256, complexfloating, inexact, number, generic, builtins.object

๐Ÿ› ๏ธ Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ“‚ (Methods and data descriptors inherited from complexfloating, inexact, number, generic would be similar to the integer case, with complex-specific methods.)

๐Ÿ“š CLASSES

๐Ÿ›๏ธ csingle = class complex64

Single-precision complex floating-point number type, compatible with C float complex.

Character code: 'F'
Canonical name: numpy.csingle
Alias: numpy.complex64: 64-bit complex floating-point number type.

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

๐Ÿ“Š Data descriptors inherited from generic:


๐Ÿ›๏ธ cdouble = class complex128

Double-precision complex floating-point number type, compatible with Python complex and C double complex.

Character code: 'D'
Canonical name: numpy.cdouble
Alias: numpy.complex128: 128-bit complex floating-point number type.

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

Same as inherited from csingle (see above).

๐Ÿ“Š Data descriptors inherited from generic:

Same as inherited from csingle (see above).


๐Ÿ›๏ธ cfloat = class complex128

Double-precision complex floating-point number type, compatible with Python complex and C double complex.

Character code: 'D'
Canonical name: numpy.cdouble
Alias: numpy.complex128

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

Same as inherited from csingle (see above).

๐Ÿ“Š Data descriptors inherited from generic:

Same as inherited from csingle (see above).


๐Ÿ›๏ธ clongdouble = class complex192 (on Linux x86_64)

Extended-precision complex floating-point number type, compatible with C long double complex but not necessarily with IEEE 754 quadruple-precision.

Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.longcomplex
Alias on this platform (Linux x86_64): numpy.complex192: 192-bit complex floating-point number type.

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

Same as inherited from csingle (see above).

๐Ÿ“Š Data descriptors inherited from generic:

Same as inherited from csingle (see above).


๐Ÿ›๏ธ clongfloat = class complex192 (on Linux x86_64)

Extended-precision complex floating-point number type, compatible with C long double complex but not necessarily with IEEE 754 quadruple-precision.

Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.longcomplex
Alias on this platform (Linux x86_64): numpy.complex192: 192-bit complex floating-point number type.

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

Same as inherited from csingle (see above).

๐Ÿ“Š Data descriptors inherited from generic:

Same as inherited from csingle (see above).


๐Ÿ›๏ธ complex64 = class complex64

Single-precision complex floating-point number type, compatible with C float complex.

Character code: 'F'
Canonical name: numpy.csingle
Alias: numpy.complex64: 64-bit complex floating-point number type.

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

Same as inherited from csingle (see above).

๐Ÿ“Š Data descriptors inherited from generic:

Same as inherited from csingle (see above).


๐Ÿ›๏ธ complex128 = class complex128

Double-precision complex floating-point number type, compatible with Python complex and C double complex.

Character code: 'D'
Canonical name: numpy.cdouble
Alias: numpy.complex128: 128-bit complex floating-point number type.

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

Same as inherited from csingle (see above).

๐Ÿ“Š Data descriptors inherited from generic:

Same as inherited from csingle (see above).


๐Ÿ›๏ธ complex192 = class complex192

Extended-precision complex floating-point number type, compatible with C long double complex but not necessarily with IEEE 754 quadruple-precision.

Character code: 'G'
Canonical name: numpy.longcomplex
Alias: numpy.complex192: 192-bit complex floating-point number type.

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

Same as inherited from csingle (see above).

๐Ÿ“Š Data descriptors inherited from generic:

Same as inherited from csingle (see above).


๐Ÿ›๏ธ complex256 = class complex256

Quarter-precision complex floating-point number type, compatible with C float complex? (Platform-specific)

Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.complex256: 256-bit complex floating-point number type.

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from complexfloating:

๐Ÿ” Methods inherited from generic:

Same as inherited from csingle (see above).

๐Ÿ“Š Data descriptors inherited from generic:

Same as inherited from csingle (see above).


๐Ÿ›๏ธ compound = class generic

Compound data type, used for structured arrays.

Character code: 'V'

Method resolution order:

See help(type) for accurate signature.

๐Ÿ”ง Methods defined here:

โš™๏ธ Static methods defined here:

๐Ÿ” Methods inherited from generic:

๐Ÿ“Š Data descriptors inherited from generic:

๐Ÿ“š CLASSES

๐Ÿ› ๏ธ ndarray Methods

๐Ÿ› ๏ธ tobytes(...)

๐Ÿ“ฅ Parameters: order : {'C', 'F', 'A'}, optional. Default 'C'.

๐Ÿ“ค Returns: s : bytes โ€“ Python bytes exhibiting a copy of a's raw data.

๐Ÿ’ก Example:

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

๐Ÿ› ๏ธ tofile(...)

๐Ÿ“ฅ Parameters: fid : file or str or Path | sep : str (default "") | format : str (default "%s")

๐Ÿ“ Notes: Always writes in 'C' order. Data can be recovered via fromfile(). Writing binary with sep="" is equivalent to file.write(a.tobytes()).

โš ๏ธ Limitations: Endianness/precision lost; not for archival. Cannot be used with compressed files or objects without fileno().

๐Ÿ› ๏ธ tostring(...)

๐Ÿ—‘๏ธ Deprecated since 1.19.0. Alias for tobytes.

๐Ÿ› ๏ธ trace(...)

๐Ÿ”— See numpy.trace.

๐Ÿ› ๏ธ transpose(...)

๐Ÿ“ฅ Parameters: axes : None, tuple of ints, or n ints.

๐Ÿ“ค Returns: out : ndarray โ€“ view with axes permuted.

๐Ÿ’ก Example:

>>> a = np.array([[1, 2], [3, 4]])
>>> a.transpose()
array([[1, 3],
       [2, 4]])

๐Ÿ› ๏ธ view(...)

๐Ÿ“ฅ Parameters: dtype (optional), type (optional).

โš ๏ธ Notes: Two uses โ€“ reinterpret dtype or return subclass instance. Behavior depends on memory layout.

๐Ÿ’ก Examples:

>>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
>>> y = x.view(dtype=np.int16, type=np.matrix)
>>> y
matrix([[513]], dtype=int16)

๐Ÿ“Š Data Descriptors inherited from ndarray

๐Ÿงฉ class memmap

memmap(filename, dtype=<class 'numpy.uint8'>, mode='r+', offset=0, shape=None, order='C')

๐Ÿ“ Create a memory-map to an array stored in a binary file on disk.

๐Ÿ“ฅ Parameters:

๐Ÿ“Ž Attributes: filename, offset, mode.

๐Ÿ› ๏ธ Methods: flush โ€“ writes changes to disk.

โš ๏ธ Notes: Cannot be larger than 2GB on 32-bit systems. Extending file beyond current size fills with zero bytes on POSIX.

๐Ÿ’ก Examples:

>>> data = np.arange(12, dtype='float32')
>>> data.resize((3,4))
>>> from tempfile import mkdtemp
>>> import os.path as path
>>> filename = path.join(mkdtemp(), 'newfile.dat')
>>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
>>> fp[:] = data[:]
>>> fp.flush()
>>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
>>> newfp
memmap([[  0.,   1.,   2.,   3.],
        [  4.,   5.,   6.,   7.],
        [  8.,   9.,  10.,  11.]], dtype=float32)

๐Ÿ—๏ธ class ndarray

ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)

An array object represents a multidimensional, homogeneous array of fixed-size items.

๐Ÿ“ฅ Parameters (for __new__):

๐Ÿ“Ž Attributes: T, data, dtype, flags, flat, imag, real, size, itemsize, nbytes, ndim, shape, strides, ctypes, base.

๐Ÿ“ Notes: Two modes of creation (buffer vs None). No __init__ needed.

๐Ÿ’ก Examples:

>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
       [     nan, 2.5e-323]])
>>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int)
array([2, 3])

๐Ÿ› ๏ธ Methods of ndarray

๐Ÿ—‚๏ธ Data and other attributes

๐Ÿ“ฆ CLASSES

๐Ÿ”ง ndarray

ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)

Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level constructor (ndarray(โ€ฆ)) for instantiating an array.

For more information, refer to the numpy module and examine the methods and attributes of an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray โ€“ Array object with given shape, dtype, order.

๐Ÿ”— See Also

๐Ÿ“ Notes

There are two modes of creating an array using __new__:

  1. If buffer is None, then only shape, dtype, and order are used.
  2. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

No __init__ method is needed because the array is fully initialized after __new__.

๐Ÿ’ก Examples

These examples illustrate the low-level ndarray constructor:

>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000],
       [    nan,     nan]]) # uninitialized
>>> np.ndarray((2,), buffer=np.array([1,2,3]),
...            offset=np.int_().itemsize,
...            dtype=int) # offset = 8 bytes
array([2, 3])

From an iterable, use np.array:

>>> np.array([[1,2],[3,4]])
array([[1, 2],
       [3, 4]])

๐Ÿ”ง Methods defined here

โš™๏ธ Static methods defined here

๐Ÿ“‹ Data descriptors defined here

๐Ÿ—ƒ๏ธ Data and other attributes defined here


๐Ÿ”ง ndenumerate

ndenumerate(arr)

Multidimensional index iterator. Returns an iterator yielding pairs of array coordinates and values.

๐Ÿ“ฅ Parameters

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> for index, x in np.ndenumerate(a):
...     print(index, x)
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4

๐Ÿ”ง Methods defined here

๐Ÿ“‹ Data descriptors defined here


๐Ÿ”ง ndindex

ndindex(*shape)

An N-dimensional iterator object to index arrays. Given the shape of an array, iterates over the N-dimensional index.

๐Ÿ“ฅ Parameters

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> for index in np.ndindex(3, 2, 1):
...     print(index)
(0, 0, 0)
(0, 1, 0)
(1, 0, 0)
(1, 1, 0)
(2, 0, 0)
(2, 1, 0)

๐Ÿ”ง Methods defined here

๐Ÿ“‹ Data descriptors defined here


๐Ÿ”ง nditer

nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', op_axes=None, itershape=None, buffersize=0)

Efficient multi-dimensional iterator object to iterate over arrays.

๐Ÿ“ฅ Parameters

๐Ÿท๏ธ Attributes

๐Ÿ“ Notes

nditer supersedes flatiter. The iterator implementation is also exposed by the NumPy C API.

๐Ÿ’ก Examples

>>> def iter_add_py(x, y, out=None):
...     addop = np.add
...     it = np.nditer([x, y, out], [],
...             [['readonly'], ['readonly'], ['writeonly','allocate']])
...     with it:
...         for (a, b, c) in it:
...             addop(a, b, out=c)
...     return it.operands[2]
>>> a = np.arange(2)+1
>>> b = np.arange(3)+1
>>> outer_it(a,b)
array([[1, 2, 3],
       [2, 4, 6]])

๐Ÿ”ง Methods defined here

๐Ÿ“‹ Data descriptors defined here


๐Ÿ”ง number

Abstract base class of all numeric scalar types.

๐Ÿ“Š Method resolution order

number โ†’ generic โ†’ builtins.object

๐Ÿ”ง Methods inherited from generic

๐Ÿ“‹ Data descriptors inherited from generic

๐Ÿ—ƒ๏ธ Data and other attributes inherited from generic


๐Ÿ”ง object_

Any Python object. Character code: 'O'

๐Ÿ“Š Method resolution order

object_ โ†’ generic โ†’ builtins.object

๐Ÿ”ง Methods defined here

โš™๏ธ Static methods defined here

๐Ÿ”ง Methods inherited from generic

Same as for number class above.

๐Ÿ“‹ Data descriptors inherited from generic

Same as for number class above.

๐Ÿ“ฆ CLASSES

๐Ÿ”ง class generic(builtins.object)

๐Ÿ”ง Methods defined here

The following methods are scalar methods identical to the corresponding array attribute. Please see ndarray for details.

๐Ÿ“‹ Data descriptors inherited from generic


๐Ÿ”ง class poly1d(builtins.object)

A one-dimensional polynomial class.

Note: This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

A convenience class, used to encapsulate "natural" operations on polynomials so that said operations may take on their customary form in code (see Examples).

๐Ÿ“ฅ Parameters

๐Ÿ“– Examples

>>> p = np.poly1d([1, 2, 3])
>>> print(np.poly1d(p))
   2
1 x + 2 x + 3
>>> p(0.5)
4.25
>>> p.r
array([-1.+1.41421356j, -1.-1.41421356j])
>>> p(p.r)
array([ -4.44089210e-16+0.j,  -4.44089210e-16+0.j]) # may vary

These numbers in the previous line represent (0, 0) to machine precision.

>>> p.c
array([1, 2, 3])
>>> p.order
2
>>> p[1]
2

Polynomials can be added, subtracted, multiplied, and divided (returns quotient and remainder):

>>> p * p
poly1d([ 1,  4, 10, 12,  9])
>>> (p**3 + 4) / p
(poly1d([ 1.,  4., 10., 12.,  9.]), poly1d([4.]))
>>> p**2 # square of polynomial
poly1d([ 1,  4, 10, 12,  9])
>>> np.square(p) # square of individual coefficients
array([1, 4, 9])
>>> p = np.poly1d([1,2,3], variable='z')
>>> print(p)
   2
1 z + 2 z + 3
>>> np.poly1d([1, 2], True)
poly1d([ 1., -3.,  2.])
>>> np.poly1d([1, -1]) * np.poly1d([1, -2])
poly1d([ 1, -3,  2])

๐Ÿ”ง Methods defined here

๐Ÿ” Readonly properties defined here

๐Ÿ“‹ Data descriptors defined here

๐Ÿ“ฆ Data and other attributes defined here


๐Ÿ”ง class recarray(ndarray)

Construct an ndarray that allows field access using attributes.

Arrays may have a data-types containing fields, analogous to columns in a spread sheet. An example is [(x, int), (y, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['x'] and arr['y']. Record arrays allow the fields to be accessed as members of the array, using arr.x and arr.y.

๐Ÿ“ฅ Parameters

โš™๏ธ Other Parameters

๐Ÿ“ค Returns

๐Ÿ“š See Also

๐Ÿ“ Notes

This constructor can be compared to empty: it creates a new record array but does not fill it with data. To create a record array from data, use one of the following methods:

  1. Create a standard ndarray and convert it to a record array, using arr.view(np.recarray)
  2. Use the buf keyword.
  3. Use np.rec.fromrecords.

๐Ÿ“– Examples

>>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', '<f8'), ('y', '<i8')])
>>> x
array([(1., 2), (3., 4)], dtype=[('x', '<f8'), ('y', '<i8')])
>>> x['x']
array([1., 3.])
>>> x = x.view(np.recarray)
>>> x.x
array([1., 3.])
>>> x.y
array([2, 4])
>>> np.recarray((2,),
... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP
rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
       (3471280, 1.2134086255804012e-316, 0)],
      dtype=[('x', '<i4'), ('y', '<f8'), ('z', '<i4')])

๐Ÿท๏ธ Method resolution order

๐Ÿ”ง Methods defined here

โš™๏ธ Static methods defined here

๐Ÿ“‹ Data descriptors defined here

๐Ÿ”ง Methods inherited from ndarray

The following methods are inherited from ndarray and are scalar methods identical to the corresponding array attribute. Please see ndarray for details.

๐Ÿ“‹ Data descriptors inherited from ndarray

๐Ÿ“ฆ Data and other attributes inherited from ndarray


๐Ÿ”ง class record(void)

A data-type scalar that allows field access as attribute lookup.

๐Ÿท๏ธ Method resolution order

๐Ÿ”ง Methods defined here

๐Ÿ“‹ Data descriptors defined here

๐Ÿ”ง Methods inherited from void

โš™๏ธ Static methods inherited from void

๐Ÿ“‹ Data descriptors inherited from void

๐Ÿ”ง Methods inherited from generic

The following methods are scalar methods identical to the corresponding array attribute. Please see ndarray for details.

๐Ÿ“‹ Data descriptors inherited from generic


๐Ÿ”ง class short = int16(signedinteger)

Signed integer type, compatible with C short.

๐Ÿท๏ธ Method resolution order

๐Ÿ”ง Methods defined here

โš™๏ธ Static methods defined here

๐Ÿ”ง Methods inherited from integer

๐Ÿ“‹ Data descriptors inherited from integer

๐Ÿ”ง Methods inherited from generic

The following methods are scalar methods identical to the corresponding array attribute. Please see ndarray for details.

๐Ÿ“š CLASSES

๐Ÿ“ฆ generic

Abstract base class of all NumPy scalar types.

๐Ÿ›  Methods defined here:

๐Ÿ“‹ Data descriptors inherited from generic:

__hash__ = None


๐Ÿ”ข signedinteger

Abstract base class of all signed integer scalar types.

Method resolution order: signedinteger โ†’ integer โ†’ number โ†’ generic โ†’ builtins.object

๐Ÿ›  Methods inherited from integer:

๐Ÿ“‹ Data descriptors inherited from integer:

๐Ÿ”„ Methods inherited from generic:

All scalar methods identical to the corresponding array attribute. Includes: __abs__, __add__, __and__, __array__, __array_wrap__, __bool__, __copy__, __deepcopy__, __divmod__, __eq__, __float__, __floordiv__, __format__, __ge__, __getitem__, __gt__, __int__, __invert__, __le__, __lshift__, __lt__, __mod__, __mul__, __ne__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __rmod__, __rmul__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __setstate__, __sizeof__, __sub__, __truediv__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.

๐Ÿ“‹ Data descriptors inherited from generic:

Same as listed in generic class above.


๐Ÿ’ง float32 (single precision)

Singleโ€‘precision floatingโ€‘point number type, compatible with C float.

Character code: 'f'   Canonical name: numpy.single   Alias on this platform: numpy.float32: 32โ€‘bitโ€‘precision: sign bit, 8 bits exponent, 23 bits mantissa.

Method resolution order: float32 โ†’ floating โ†’ inexact โ†’ number โ†’ generic โ†’ builtins.object

๐Ÿ›  Methods defined here:

โš™ Static methods defined here:

๐Ÿ”„ Methods inherited from floating:

๐Ÿ”„ Methods inherited from generic:

All scalar methods identical to the corresponding array attribute. Includes: __and__, __array__, __array_wrap__, __copy__, __deepcopy__, __format__, __getitem__, __invert__, __lshift__, __or__, __rand__, __reduce__, __rlshift__, __ror__, __rrshift__, __rshift__, __rxor__, __setstate__, __sizeof__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.

๐Ÿ“‹ Data descriptors inherited from generic:

Same as listed in generic class above.


๐ŸŒ€ complex64 (singlecomplex)

Complex number type composed of two singleโ€‘precision floatingโ€‘point numbers.

Character code: 'F'   Canonical name: numpy.csingle   Alias: numpy.singlecomplex   Alias on this platform: numpy.complex64: 2 ร— 32โ€‘bit precision.

Method resolution order: complex64 โ†’ complexfloating โ†’ inexact โ†’ number โ†’ generic โ†’ builtins.object

๐Ÿ›  Methods defined here:

โš™ Static methods defined here:

๐Ÿ”„ Methods inherited from complexfloating:

๐Ÿ”„ Methods inherited from generic:

All scalar methods identical to the corresponding array attribute. Includes: __and__, __array__, __array_wrap__, __copy__, __deepcopy__, __divmod__, __format__, __getitem__, __invert__, __lshift__, __mod__, __or__, __rand__, __rdivmod__, __reduce__, __rlshift__, __rmod__, __ror__, __rrshift__, __rshift__, __rxor__, __setstate__, __sizeof__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.

๐Ÿ“‹ Data descriptors inherited from generic:

Same as listed in generic class above.


๐Ÿ“ str0 (str_)

A unicode string. When used in arrays, this type strips trailing null codepoints. Unlike the builtin str, this supports the buffer protocol, exposing its contents as UCS4.

Character code: 'U'   Alias: numpy.unicode_

Method resolution order: str_ โ†’ builtins.str โ†’ character โ†’ flexible โ†’ generic โ†’ builtins.object

๐Ÿ›  Methods defined here:

โš™ Static methods defined here:

๐Ÿ”„ Methods inherited from builtins.str:

All standard string methods: __add__, __contains__, __format__, __getattribute__, __getitem__, __getnewargs__, __iter__, __len__, __mod__, __mul__, __rmod__, __rmul__, __sizeof__, capitalize, casefold, center, count, encode, endswith, expandtabs, find, format, format_map, index, isalnum, isalpha, isascii, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupper, join, ljust, lower, lstrip, partition, removeprefix, removesuffix, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill. Static method maketrans.

๐Ÿ”„ Methods inherited from generic:

All scalar methods identical to the corresponding array attribute. Includes: __abs__, __and__, __array__, __array_wrap__, __bool__, __copy__, __deepcopy__, __divmod__, __float__, __floordiv__, __int__, __invert__, __lshift__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __setstate__, __sub__, __truediv__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.

๐Ÿ“‹ Data descriptors inherited from generic:

Same as listed in generic class above.


๐Ÿ“œ string_ (bytes_)

A byte string. When used in arrays, this type strips trailing null bytes.

Character code: 'S'   Alias: numpy.string_

Method resolution order: bytes_ โ†’ builtins.bytes โ†’ character โ†’ flexible โ†’ generic โ†’ builtins.object

๐Ÿ›  Methods defined here:

โš™ Static methods defined here:

๐Ÿ”„ Methods inherited from builtins.bytes:

All standard bytes methods: __add__, __contains__, __getattribute__, __getitem__, __getnewargs__, __iter__, __len__, __mod__, __mul__, __rmod__, __rmul__, capitalize, center, count, decode, endswith, expandtabs, find, hex, index, isalnum, isalpha, isascii, isdigit, islower, isspace, istitle, isupper, join, ljust, lower, lstrip, partition, removeprefix, removesuffix, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill.

๐Ÿ”„ Methods inherited from generic:

All scalar methods identical to the corresponding array attribute. Includes: __abs__, __and__, __array__, __array_wrap__, __bool__, __copy__, __deepcopy__, __divmod__, __float__, __floordiv__, __int__, __invert__, __lshift__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __setstate__, __sub__, __truediv__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.

๐Ÿ“‹ Data descriptors inherited from generic:

Same as listed in generic class above.

๐Ÿงฉ CLASSES

๐Ÿ”น generic (from builtins.object)

Base class for all NumPy scalars.

๐Ÿ“‹ Methods defined here:

๐Ÿ“ฆ Class methods inherited from builtins.bytes:

๐Ÿ› ๏ธ Static methods inherited from builtins.bytes:

๐Ÿงฌ Methods inherited from generic (scalar base):

๐Ÿ“Š Data descriptors inherited from generic:


๐Ÿ”น timedelta64 (signedinteger)

A timedelta stored as a 64-bit integer. Character code: 'm'.

๐Ÿ“‹ Methods defined here:

๐Ÿ› ๏ธ Static methods:

๐Ÿงฌ Methods inherited from integer:

๐Ÿ“Š Data descriptors inherited from integer:

All other methods and data descriptors are inherited from generic (see above).


๐Ÿ”น ufunc (builtins.object)

Functions that operate element by element on whole arrays. Calling syntax: op(*x[, out], where=True, **kwargs).

๐Ÿ“‹ Methods defined here:

๐Ÿ“Š Data descriptors:


๐Ÿ”น uint8 (unsignedinteger) โ€” alias: ubyte

Unsigned integer type, compatible with C unsigned char. Character code: 'B'. Range: 0 to 255.

๐Ÿ“‹ Methods defined here:

๐Ÿ› ๏ธ Static methods:

๐Ÿงฌ Methods inherited from integer:

๐Ÿ“Š Data descriptors inherited from integer:

All methods and data descriptors from generic are also inherited (see generic class above).


๐Ÿ”น uint16 (unsignedinteger) โ€” alias: ushort

Unsigned integer type, compatible with C unsigned short. Character code: 'H'. Range: 0 to 65,535.

๐Ÿ“‹ Methods defined here:

Identical to uint8 methods (same set of arithmetic and comparison operators).

๐Ÿงฌ Inherited methods and data descriptors:

Same as uint8 (inherits from integer and generic).


๐Ÿ”น uint32 (unsignedinteger) โ€” alias: uintc

Unsigned integer type, compatible with C unsigned int. Character code: 'I'. Range: 0 to 4,294,967,295.

๐Ÿ“‹ Methods defined here:

Identical to uint8 methods.

๐Ÿงฌ Inherited methods and data descriptors:

Same as uint8.


๐Ÿ”น uint64 (unsignedinteger) โ€” aliases: uint, uint0

Unsigned integer type, compatible with C unsigned long. Character code: 'L'. Range: 0 to 18,446,744,073,709,551,615. Also aliased as uintp (unsigned integer large enough to fit a pointer).

๐Ÿ“‹ Methods defined here:

Identical to uint8 methods.

๐Ÿงฌ Inherited methods and data descriptors:

Same as uint8.


Note: The classes uint8, uint16, uint32, and uint64 share the same set of methods inherited from unsignedinteger, integer, and generic. Only the character code, canonical name, and range differ.

๐Ÿ“ฆ CLASSES

๐Ÿ”ง Scalar Methods & Data Descriptors (Continuation)

The default value ('S') results in swapping the current byte order.

๐Ÿ”ง Scalar methods:

๐Ÿ”ฌ Data descriptors inherited from generic:

๐Ÿ”ข class uint64 (inherits from unsignedinteger)

Unsigned integer type, compatible with C unsigned long.

๐Ÿ“‹ Method resolution order:

  1. uint64
  2. unsignedinteger
  3. integer
  4. number
  5. generic
  6. builtins.object

๐Ÿ”ง Methods defined here:

๐Ÿ”ง Static methods defined here:

๐Ÿ“‚ Methods inherited from integer:

๐Ÿ”ฌ Data descriptors inherited from integer:

๐Ÿ“‚ Methods inherited from generic:

๐Ÿ”ฌ Data descriptors inherited from generic:

๐Ÿ”ข class uint8 (inherits from unsignedinteger)

Unsigned integer type, compatible with C unsigned char.

๐Ÿ“‹ Method resolution order:

  1. uint8
  2. unsignedinteger
  3. integer
  4. number
  5. generic
  6. builtins.object

Methods, data descriptors, and inherited sections are identical to those of class uint64 above.

๐Ÿ”ข class uintc (alias for uint32, inherits from unsignedinteger)

Unsigned integer type, compatible with C unsigned int.

๐Ÿ“‹ Method resolution order:

  1. uint32
  2. unsignedinteger
  3. integer
  4. number
  5. generic
  6. builtins.object

Methods, data descriptors, and inherited sections are identical to those of class uint64 above.

๐Ÿ”ข class uintp (alias for uint64, inherits from unsignedinteger)

Unsigned integer type, compatible with C unsigned long.

๐Ÿ“‹ Method resolution order:

  1. uint64
  2. unsignedinteger
  3. integer
  4. number
  5. generic
  6. builtins.object

Methods, data descriptors, and inherited sections are identical to those of class uint64 above.

๐Ÿ”ข class ulonglong (inherits from unsignedinteger)

Signed integer type, compatible with C unsigned long long.

๐Ÿ“‹ Method resolution order:

  1. ulonglong
  2. unsignedinteger
  3. integer
  4. number
  5. generic
  6. builtins.object

Methods, data descriptors, and inherited sections are identical to those of class uint64 above.

๐Ÿ”ข class unicode_ (inherits from builtins.str and character)

A unicode string. When used in arrays, this type strips trailing null codepoints. Unlike the builtin str, this supports the buffer protocol, exposing its contents as UCS4:

>>> m = memoryview(np.str_("abc"))
>>> m.format
'3w'
>>> m.tobytes()
b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'

๐Ÿ“‹ Method resolution order:

  1. str_
  2. builtins.str
  3. character
  4. flexible
  5. generic
  6. builtins.object

๐Ÿ”ง Methods defined here:

๐Ÿ”ง Static methods defined here:

๐Ÿ“‚ Methods inherited from builtins.str:

๐Ÿ”ง Static methods inherited from builtins.str:

๐Ÿ“‚ Methods inherited from generic:

๐Ÿ”ฌ Data descriptors inherited from generic:

๐Ÿ”ข class unsignedinteger (inherits from integer)

Abstract base class of all unsigned integer scalar types.

๐Ÿ“‹ Method resolution order:

  1. unsignedinteger
  2. integer
  3. number
  4. generic
  5. builtins.object

Methods, data descriptors, and inherited sections are identical to those of class uint64 above.

๐Ÿ“ฆ CLASSES

๐Ÿ”ข ushort = class uint16(unsignedinteger)

Unsigned integer type, compatible with C unsigned short.

๐Ÿงฌ Character code: 'H'
๐Ÿท๏ธ Canonical name: numpy.ushort
๐Ÿ”— Alias on this platform (Linux x86_64): numpy.uint16: 16-bit unsigned integer (0 to 65_535).

๐Ÿ“‹ Method resolution order:

โš™๏ธ Methods defined here:

๐Ÿ”ง Static methods defined here:

โฌ‡๏ธ Methods inherited from integer:

๐Ÿ“Š Data descriptors inherited from integer:

โฌ‡๏ธ Methods inherited from generic:

๐Ÿ”„ Scalar methods (identical to corresponding array attribute):

๐Ÿ“ Data descriptors inherited from generic:

๐Ÿ”ข Data and other attributes inherited from generic:


๐Ÿ”„ vectorize = class vectorize(builtins.object)

vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None)

Generalized function class.

Define a vectorized function which takes a nested sequence of objects or numpy arrays as inputs and returns a single numpy array or a tuple of numpy arrays. The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy.

The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided by specifying the otypes argument.

๐Ÿ“ฅ Parameters:

๐Ÿ“ค Returns:

๐Ÿ‘๏ธ See Also:

๐Ÿ“ Notes:

The vectorize function is provided primarily for convenience, not for performance. The implementation is essentially a for loop.

If otypes is not specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.

The new keyword argument interface and excluded argument support further degrades performance.

๐Ÿ“š References:

.. [1] :doc:`/reference/c-api/generalized-ufuncs`

๐Ÿ’ก Examples:

>>> def myfunc(a, b):
...     "Return a-b if a>b, otherwise return a+b"
...     if a > b:
...         return a - b
...     else:
...         return a + b

>>> vfunc = np.vectorize(myfunc)
>>> vfunc([1, 2, 3, 4], 2)
array([3, 4, 1, 2])

The docstring is taken from the input function to vectorize unless it is specified:

>>> vfunc.__doc__
'Return a-b if a>b, otherwise return a+b'
>>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')
>>> vfunc.__doc__
'Vectorized `myfunc`'

The output type is determined by evaluating the first element of the input, unless it is specified:

>>> out = vfunc([1, 2, 3, 4], 2)
>>> type(out[0])
<class 'numpy.int64'>
>>> vfunc = np.vectorize(myfunc, otypes=[float])
>>> out = vfunc([1, 2, 3, 4], 2)
>>> type(out[0])
<class 'numpy.float64'>

The excluded argument can be used to prevent vectorizing over certain arguments. This can be useful for array-like arguments of a fixed length such as the coefficients for a polynomial as in polyval:

>>> def mypolyval(p, x):
...     _p = list(p)
...     res = _p.pop(0)
...     while _p:
...         res = res*x + _p.pop(0)
...     return res
>>> vpolyval = np.vectorize(mypolyval, excluded=['p'])
>>> vpolyval(p=[1, 2, 3], x=[0, 1])
array([3, 6])

Positional arguments may also be excluded by specifying their position:

>>> vpolyval.excluded.add(0)
>>> vpolyval([1, 2, 3], x=[0, 1])
array([3, 6])

The signature argument allows for vectorizing functions that act on non-scalar arrays of fixed length. For example, you can use it for a vectorized calculation of Pearson correlation coefficient and its p-value:

>>> import scipy.stats
>>> pearsonr = np.vectorize(scipy.stats.pearsonr,
...                 signature='(n),(n)->(),()')
>>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])
(array([ 1., -1.]), array([ 0.,  0.]))

Or for a vectorized convolution:

>>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')
>>> convolve(np.eye(4), [1, 2, 1])
array([[1., 2., 1., 0., 0., 0.],
       [0., 1., 2., 1., 0., 0.],
       [0., 0., 1., 2., 1., 0.],
       [0., 0., 0., 1., 2., 1.]])

โš™๏ธ Methods defined here:

๐Ÿ“Š Data descriptors defined here:


๐Ÿ“ฆ void = class void(flexible)

Either an opaque sequence of bytes, or a structure.

>>> np.void(b'abcd')
void(b'\x61\x62\x63\x64')

Structured void scalars can only be constructed via extraction from structured_arrays:

>>> arr = np.array((1, 2), dtype=[('x', np.int8), ('y', np.int8)])
>>> arr[()]
(1, 2)  # looks like a tuple, but is `np.void`

๐Ÿงฌ Character code: 'V'

๐Ÿ“‹ Method resolution order:

โš™๏ธ Methods defined here:

๐Ÿ”ง Static methods defined here:

๐Ÿ“Š Data descriptors defined here:

โฌ‡๏ธ Methods inherited from generic:

๐Ÿ”„ Scalar methods (identical to corresponding array attribute):

๐Ÿ“ Data descriptors inherited from generic:


๐Ÿ“ฆ void0 = class void(flexible)

Alias for void class. Identical in every respect. See void class above for full details.


๐Ÿ”ง FUNCTIONS

__dir__()

__getattr__(attr)

# module level getattr is only supported in 3.7 onwards
https://www.python.org/dev/peps/pep-0562/

_add_newdoc_ufunc(...)

add_ufunc_docstring(ufunc, new_docstring)

Replace the docstring for a ufunc with new_docstring. This method will only work if the current docstring for the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.)

๐Ÿ“ฅ Parameters

๐Ÿ“ Notes

This method allocates memory for new_docstring on the heap. Technically this creates a memory leak, since this memory will not be reclaimed until the end of the program even if the ufunc itself is removed. However this will only be a problem if the user is repeatedly creating ufuncs with no documentation, adding documentation via add_newdoc_ufunc, and then throwing away the ufunc.

add_docstring(...)

add_docstring(obj, docstring)

Add a docstring to a built-in obj if possible. If the obj already has a docstring raise a RuntimeError. If this routine does not know how to add a docstring to the object raise a TypeError.

add_newdoc(place, obj, doc, warn_on_python=True)

Add documentation to an existing object, typically one defined in C.

The purpose is to allow easier editing of the docstrings without requiring a re-compile. This exists primarily for internal use within numpy itself.

๐Ÿ“ฅ Parameters

๐Ÿ“ Notes

This routine never raises an error if the docstring can't be written, but will raise an error if the object being documented does not exist. This routine cannot modify read-only docstrings, as appear in new-style classes or built-in functions. Because this routine never raises an error the caller must check manually that the docstrings were changed. Since this function grabs the char * from a c-level str object and puts it into the tp_doc slot of the type of obj, it violates a number of C-API best-practices, by:

If possible it should be avoided.

add_newdoc_ufunc = _add_newdoc_ufunc(...)

Same as _add_newdoc_ufunc.

alen(a)

Return the length of the first dimension of the input array.

.. deprecated:: 1.18
numpy.alen is deprecated, use len instead.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> a = np.zeros((7,4,5))
>>> a.shape[0]
7
>>> np.alen(a)
7

all(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)

Test whether all array elements along a given axis evaluate to True.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.

๐Ÿ’ก Examples

>>> np.all([[True,False],[True,True]])
False

>>> np.all([[True,False],[True,True]], axis=0)
array([ True, False])

>>> np.all([-1, 4, 5])
True

>>> np.all([1.0, np.nan])
True

>>> np.all([[True, True], [False, True]], where=[[True], [False]])
True

>>> o=np.array(False)
>>> z=np.all([-1, 4, 5], out=o)
>>> id(z), id(o), z
(28293632, 28293632, array(True)) # may vary

allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b. NaNs are treated as equal if they are in the same place and if equal_nan=True. Infs are treated as equal if they are in the same place and of the same sign in both arrays.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

If the following equation is element-wise True, then allclose returns True.

 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

The above equation is not symmetric in a and b, so that allclose(a, b) might be different from allclose(b, a) in some rare cases. The comparison of a and b uses standard broadcasting, which means that a and b need not have the same shape in order for allclose(a, b) to evaluate to True. The same is true for equal but not array_equal.

allclose is not defined for non-numeric data types.

๐Ÿ’ก Examples

>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
False
>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
True
>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
True

alltrue(*args, **kwargs)

Check if all elements of input array are true.

๐Ÿ‘€ See Also

amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Return the maximum of an array or maximum along an axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmax. Don't use amax for element-wise comparison of 2 arrays; when a.shape[0] is 2, maximum(a[0], a[1]) is faster than amax(a, axis=0).

๐Ÿ’ก Examples

>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
       [2, 3]])
>>> np.amax(a)           # Maximum of the flattened array
3
>>> np.amax(a, axis=0)   # Maxima along the first axis
array([2, 3])
>>> np.amax(a, axis=1)   # Maxima along the second axis
array([1, 3])
>>> np.amax(a, where=[False, True], initial=-1, axis=0)
array([-1,  3])
>>> b = np.arange(5, dtype=float)
>>> b[2] = np.NaN
>>> np.amax(b)
nan
>>> np.amax(b, where=~np.isnan(b), initial=-1)
4.0
>>> np.nanmax(b)
4.0

You can use an initial value to compute the maximum of an empty slice, or
to initialize it to a different value:

>>> np.max([[-50], [10]], axis=-1, initial=0)
array([ 0, 10])

Notice that the initial value is used as one of the elements for which the
maximum is determined, unlike for the default argument Python's max
function, which is only used for empty iterables.

>>> np.max([5], initial=6)
6
>>> max([5], default=6)
5

amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Return the minimum of an array or minimum along an axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmin. Don't use amin for element-wise comparison of 2 arrays; when a.shape[0] is 2, minimum(a[0], a[1]) is faster than amin(a, axis=0).

๐Ÿ’ก Examples

>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
       [2, 3]])
>>> np.amin(a)           # Minimum of the flattened array
0
>>> np.amin(a, axis=0)   # Minima along the first axis
array([0, 1])
>>> np.amin(a, axis=1)   # Minima along the second axis
array([0, 2])
>>> np.amin(a, where=[False, True], initial=10, axis=0)
array([10,  1])

>>> b = np.arange(5, dtype=float)
>>> b[2] = np.NaN
>>> np.amin(b)
nan
>>> np.amin(b, where=~np.isnan(b), initial=10)
0.0
>>> np.nanmin(b)
0.0

>>> np.min([[-50], [10]], axis=-1, initial=0)
array([-50,   0])

Notice that the initial value is used as one of the elements for which the
minimum is determined, unlike for the default argument Python's max
function, which is only used for empty iterables. Notice that this isn't the same as Python's ``default`` argument.

>>> np.min([6], initial=5)
5
>>> min([6], default=5)
6

angle(z, deg=False)

Return the angle of the complex argument.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

Although the angle of the complex number 0 is undefined, numpy.angle(0) returns the value 0.

๐Ÿ’ก Examples

>>> np.angle([1.0, 1.0j, 1+1j])               # in radians
array([ 0.        ,  1.57079633,  0.78539816]) # may vary
>>> np.angle(1+1j, deg=True)                  # in degrees
45.0

any(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)

Test whether any array element along a given axis evaluates to True. Returns single boolean unless axis is not None.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.

๐Ÿ’ก Examples

>>> np.any([[True, False], [True, True]])
True

>>> np.any([[True, False], [False, False]], axis=0)
array([ True, False])

>>> np.any([-1, 0, 5])
True

>>> np.any(np.nan)
True

>>> np.any([[True, False], [False, False]], where=[[False], [True]])
False

>>> o=np.array(False)
>>> z=np.any([-1, 4, 5], out=o)
>>> z, o
(array(True), array(True))
>>> # Check now that z is a reference to o
>>> z is o
True
>>> id(z), id(o) # identity of z and o              # doctest: +SKIP
(191614240, 191614240)

append(arr, values, axis=None)

Append values to the end of an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, ..., 7, 8, 9])

When `axis` is specified, `values` must have the correct shape.

>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
Traceback (most recent call last):
    ... ValueError: all the input arrays must have same number of dimensions, but
the array at index 0 has 2 dimension(s) and the array at index 1 has 1
dimension(s)

apply_along_axis(func1d, axis, arr, *args, **kwargs)

Apply a function to 1-D slices along the given axis. Execute func1d(a, *args, **kwargs) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis. This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii, jj, and kk to a tuple of indices:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        f = func1d(arr[ii + s_[:,] + kk])
        Nj = f.shape
        for jj in ndindex(Nj):
            out[ii + jj + kk] = f[jj]

Equivalently, eliminating the inner loop, this can be expressed as:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> def my_func(a):
...     """Average first and last element of a 1-D array"""
...     return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([2.,  5.,  8.])

For a function that returns a 1D array, the number of dimensions in
`outarr` is the same as `arr`.

>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
       [3, 4, 9],
       [2, 5, 6]])

For a function that returns a higher dimensional array, those dimensions
are inserted in place of the `axis` dimension.

>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(np.diag, -1, b)
array([[[1, 0, 0],
        [0, 2, 0],
        [0, 0, 3]],
       [[4, 0, 0],
        [0, 5, 0],
        [0, 0, 6]],
       [[7, 0, 0],
        [0, 8, 0],
        [0, 0, 9]]])

apply_over_axes(func, a, axes)

Apply a function repeatedly over multiple axes.

func is called as res = func(a, axis), where axis is the first element of axes. The result res of the function call must have either the same dimensions as a or one less dimension. If res has one less dimension than a, a dimension is inserted before axis. The call to func is then repeated for each axis in axes, with res as the first argument.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

This function is equivalent to tuple axis arguments to reorderable ufuncs with keepdims=True. Tuple axis arguments to ufuncs have been available since version 1.7.0.

๐Ÿ’ก Examples

>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],
       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

Sum over axes 0 and 2. The result has same number of dimensions
as the original array:

>>> np.apply_over_axes(np.sum, a, [0,2])
array([[[ 60],
        [ 92],
        [124]]])

Tuple axis arguments to ufuncs are equivalent:

>>> np.sum(a, axis=(0,2), keepdims=True)
array([[[ 60],
        [ 92],
        [124]]])

arange(...)

arange([start,] stop[, step,], dtype=None, *, like=None)

Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0.,  1.,  2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])

argmax(a, axis=None, out=None)

Returns the indices of the maximum values along an axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.

๐Ÿ’ก Examples

>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10, 11, 12],
       [13, 14, 15]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])

Indexes of the maximal elements of a N-dimensional array:

>>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
>>> ind
(1, 2)
>>> a[ind]
15

>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b)  # Only the first occurrence is returned.
1

>>> x = np.array([[4,2,3], [1,0,3]])
>>> index_array = np.argmax(x, axis=-1)
>>> # Same as np.max(x, axis=-1, keepdims=True)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
array([[4],
       [3]])
>>> # Same as np.max(x, axis=-1)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
array([4, 3])

argmin(a, axis=None, out=None)

Returns the indices of the minimum values along an axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

In case of multiple occurrences of the minimum values, the indices corresponding to the first occurrence are returned.

๐Ÿ’ก Examples

>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10, 11, 12],
       [13, 14, 15]])
>>> np.argmin(a)
0
>>> np.argmin(a, axis=0)
array([0, 0, 0])
>>> np.argmin(a, axis=1)
array([0, 0])

Indices of the minimum elements of a N-dimensional array:

>>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
>>> ind
(0, 0)
>>> a[ind]
10

>>> b = np.arange(6) + 10
>>> b[4] = 10
>>> b
array([10, 11, 12, 13, 10, 15])
>>> np.argmin(b)  # Only the first occurrence is returned.
0

>>> x = np.array([[4,2,3], [1,0,3]])
>>> index_array = np.argmin(x, axis=-1)
>>> # Same as np.min(x, axis=-1, keepdims=True)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
array([[2],
       [0]])
>>> # Same as np.max(x, axis=-1)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
array([2, 0])

argpartition(a, kth, axis=-1, kind='introselect', order=None)

Perform an indirect partition along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in partitioned order.

.. versionadded:: 1.8.0

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

See partition for notes on the different selection algorithms.

๐Ÿ’ก Examples

One dimensional array:

>>> x = np.array([3, 4, 2, 1])
>>> x[np.argpartition(x, 3)]
array([2, 1, 3, 4])
>>> x[np.argpartition(x, (1, 3))]
array([1, 2, 3, 4])

>>> x = [3, 4, 2, 1]
>>> np.array(x)[np.argpartition(x, 3)]
array([2, 1, 3, 4])

Multi-dimensional array:

>>> x = np.array([[3, 4, 2], [1, 3, 1]])
>>> index_array = np.argpartition(x, kth=1, axis=-1)
>>> np.take_along_axis(x, index_array, axis=-1)  # same as np.partition(x, kth=1)
array([[2, 3, 4],
       [1, 1, 3]])

argsort(a, axis=-1, kind=None, order=None)

Returns the indices that would sort an array. Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in sorted order.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

See sort for notes on the different sorting algorithms. As of NumPy 1.4.0 argsort works with real/complex arrays containing nan values. The enhanced sort order is documented in sort.

๐Ÿ’ก Examples

One dimensional array:

>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])

Two-dimensional array:

>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
       [2, 2]])

>>> ind = np.argsort(x, axis=0)  # sorts along first axis (down)
>>> ind
array([[0, 1],
       [1, 0]])
>>> np.take_along_axis(x, ind, axis=0)  # same as np.sort(x, axis=0)
array([[0, 2],
       [2, 3]])

>>> ind = np.argsort(x, axis=1)  # sorts along last axis (across)
>>> ind
array([[0, 1],
       [0, 1]])
>>> np.take_along_axis(x, ind, axis=1)  # same as np.sort(x, axis=1)
array([[0, 3],
       [2, 2]])

Indices of the sorted elements of a N-dimensional array:

>>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
>>> ind
(array([0, 1, 1, 0]), array([0, 0, 1, 1]))
>>> x[ind]  # same as np.sort(x, axis=None)
array([0, 2, 2, 3])

Sorting with keys:

>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
array([(1, 0), (0, 1)],
      dtype=[('x', '<i4'), ('y', '<i4')])

>>> np.argsort(x, order=('x','y'))
array([1, 0])

>>> np.argsort(x, order=('y','x'))
array([0, 1])

argwhere(a)

Find the indices of array elements that are non-zero, grouped by element.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

np.argwhere(a) is almost the same as np.transpose(np.nonzero(a)), but produces a result of the correct shape for a 0D array. The output of argwhere is not suitable for indexing arrays. For this purpose use nonzero(a) instead.

๐Ÿ’ก Examples

>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
       [1, 0],
       [1, 1],
       [1, 2]])

around(a, decimals=0, out=None)

Evenly round to the given number of decimals.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc.

np.around uses a fast but sometimes inexact algorithm to round floating-point datatypes. For positive decimals it is equivalent to np.true_divide(np.rint(a * 10**decimals), 10**decimals), which has error due to the inexact representation of decimal fractions in the IEEE floating point standard [1]_ and errors introduced when scaling by powers of ten. For instance, note the extra "1" in the following:

>>> np.round(56294995342131.5, 3)
56294995342131.51

If your goal is to print such values with a fixed number of decimals, it is preferable to use numpy's float printing routines to limit the number of printed decimals:

>>> np.format_float_positional(56294995342131.5, precision=3)
'56294995342131.5'

The float printing routines use an accurate but much more computationally demanding algorithm to compute the number of digits after the decimal point. Alternatively, Python's builtin round function uses a more accurate but slower algorithm for 64-bit floating point values:

>>> round(56294995342131.5, 3)
56294995342131.5
>>> np.round(16.055, 2), round(16.055, 2)  # equals 16.0549999999999997
(16.06, 16.05)

๐Ÿ“š References

๐Ÿ’ก Examples

>>> np.around([0.37, 1.64])
array([0.,  2.])
>>> np.around([0.37, 1.64], decimals=1)
array([0.4,  1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([0.,  2.,  2.,  4.,  4.])
>>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1,  2,  3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])

array(...)

array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)

Create an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

When order is 'A' and object is an array in neither 'C' nor 'F' order, and a copy is forced by a change in dtype, then the order of the result is not necessarily 'C' as expected. This is likely a bug.

๐Ÿ’ก Examples

>>> np.array([1, 2, 3])
array([1, 2, 3])

Upcasting:

>>> np.array([1, 2, 3.0])
array([ 1.,  2.,  3.])

More than one dimension:

>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
       [3, 4]])

Minimum dimensions 2:

>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])

Type provided:

>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j,  2.+0.j,  3.+0.j])

Data-type consisting of more than one element:

>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])

Creating an array from sub-classes:

>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
       [3, 4]])

>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
        [3, 4]])

array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix='', style=<no value>, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix='', *, legacy=None)

Return a string representation of an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘€ See Also

๐Ÿ“ Notes

If a formatter is specified for a certain type, the precision keyword is ignored for that type. This is a very flexible function; array_repr and array_str are using array2string internally so keywords with the same name should work identically in all three functions.

๐Ÿ’ก Examples

>>> x = np.array([1e-16,1,2,3])
>>> np.array2string(x, precision=2, separator=',',
...                       suppress_small=True)
'[0.,1.,2.,3.]'

>>> x  = np.arange(3.)
>>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
'[0.00 1.00 2.00]'

>>> x  = np.arange(3)
>>> np.array2string(x, formatter={'int':lambda x: hex(x)})
'[0x0 0x1 0x2]'

array_equal(a1, a2, equal_nan=False)

True if two arrays have the same shape and elements, False otherwise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.array_equal([1, 2], [1, 2])
True
>>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
>>> np.array_equal([1, 2], [1, 2, 3])
False
>>> np.array_equal([1, 2], [1, 4])
False
>>> a = np.array([1, np.nan])
>>> np.array_equal(a, a)
False
>>> np.array_equal(a, a, equal_nan=True)
True

When ``equal_nan`` is True, complex values with nan components are
considered equal if either the real *or* the imaginary components are nan.

>>> a = np.array([1 + 1j])
>>> b = a.copy()
>>> a.real = np.nan
>>> b.imag = np.nan
>>> np.array_equal(a, b, equal_nan=True)
True

array_equiv(a1, a2)

Returns True if input arrays are shape consistent and all elements equal. Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same shape as the other one.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> np.array_equiv([1, 2], [1, 2])
True
>>> np.array_equiv([1, 2], [1, 3])
False

Showing the shape equivalence:

>>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
True
>>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
False

>>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
False

array_repr(arr, max_line_width=None, precision=None, suppress_small=None)

Return the string representation of an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.array_repr(np.array([1,2]))
'array([1, 2])'
>>> np.array_repr(np.ma.array([0.]))
'MaskedArray([0.])'
>>> np.array_repr(np.array([], np.int32))
'array([], dtype=int32)'

>>> x = np.array([1e-6, 4e-7, 2, 3])
>>> np.array_repr(x, precision=6, suppress_small=True)
'array([0.000001,  0.      ,  2.      ,  3.      ])'

array_split(ary, indices_or_sections, axis=0)

Split an array into multiple sub-arrays. Please refer to the split documentation. The only difference between these functions is that array_split allows indices_or_sections to be an integer that does *not* equally divide the axis. For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([0.,  1.,  2.]), array([3.,  4.,  5.]), array([6.,  7.])]

>>> x = np.arange(9)
>>> np.array_split(x, 4)
[array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]

array_str(a, max_line_width=None, precision=None, suppress_small=None)

Return a string representation of the data in an array. The data in the array is returned as a single string. This function is similar to array_repr, the difference being that array_repr also returns information on the kind of array and its data type.

๐Ÿ“ฅ Parameters

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.array_str(np.arange(3))
'[0 1 2]'

asanyarray(...)

asanyarray(a, dtype=None, order=None, *, like=None)

Convert the input to an ndarray, but pass ndarray subclasses through.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

Convert a list into an array:

>>> a = [1, 2]
>>> np.asanyarray(a)
array([1, 2])

Instances of `ndarray` subclasses are passed through as-is:

>>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
>>> np.asanyarray(a) is a
True

asarray(...)

asarray(a, dtype=None, order=None, *, like=None)

Convert the input to an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

Convert a list into an array:

>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])

Existing arrays are not copied:

>>> a = np.array([1, 2])
>>> np.asarray(a) is a
True

If `dtype` is set, array is copied only if dtype does not match:

>>> a = np.array([1, 2], dtype=np.float32)
>>> np.asarray(a, dtype=np.float32) is a
True
>>> np.asarray(a, dtype=np.float64) is a
False

Contrary to `asanyarray`, ndarray subclasses are not passed through:

>>> issubclass(np.recarray, np.ndarray)
True
>>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
>>> np.asarray(a) is a
False
>>> np.asanyarray(a) is a
True

asarray_chkfinite(a, dtype=None, order=None)

Convert the input to an array, checking for NaNs or Infs.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

Convert a list into an array. If all elements are finite
``asarray_chkfinite`` is identical to ``asarray``.

>>> a = [1, 2]
>>> np.asarray_chkfinite(a, dtype=float)
array([1., 2.])

Raises ValueError if array_like contains Nans or Infs.

>>> a = [1, 2, np.inf]
>>> try:
...     np.asarray_chkfinite(a)
... except ValueError:
...     print('ValueError')
... ValueError

ascontiguousarray(...)

ascontiguousarray(a, dtype=None, *, like=None)

Return a contiguous array (ndim >= 1) in memory (C order).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> x = np.arange(6).reshape(2,3)
>>> np.ascontiguousarray(x, dtype=np.float32)
array([[0., 1., 2.],
       [3., 4., 5.]], dtype=float32)
>>> x.flags['C_CONTIGUOUS']
True

Note: This function returns an array with at least one-dimension (1-d)
so it will not preserve 0-d arrays.

asfarray(a, dtype=<class 'numpy.float64'>)

Return an array converted to a float type.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> np.asfarray([2, 3])
array([2.,  3.])
>>> np.asfarray([2, 3], dtype='float')
array([2.,  3.])
>>> np.asfarray([2, 3], dtype='int8')
array([2.,  3.])

asfortranarray(...)

asfortranarray(a, dtype=None, *, like=None)

Return an array (ndim >= 1) laid out in Fortran order in memory.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> x = np.arange(6).reshape(2,3)
>>> y = np.asfortranarray(x)
>>> x.flags['F_CONTIGUOUS']
False
>>> y.flags['F_CONTIGUOUS']
True

Note: This function returns an array with at least one-dimension (1-d)
so it will not preserve 0-d arrays.

asmatrix(data, dtype=None)

Interpret the input as a matrix. Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to matrix(data, copy=False).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> x = np.array([[1, 2], [3, 4]])

>>> m = np.asmatrix(x)

>>> x[0,0] = 5

>>> m
matrix([[5, 2],
        [3, 4]])

asscalar(a)

Convert an array of size 1 to its scalar equivalent.

.. deprecated:: 1.16
Deprecated, use numpy.ndarray.item() instead.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> np.asscalar(np.array([24]))
24

atleast_1d(*arys)

Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.atleast_1d(1.0)
array([1.])

>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[0., 1., 2.],
       [3., 4., 5.],
       [6., 7., 8.]])
>>> np.atleast_1d(x) is x
True

>>> np.atleast_1d(1, [3, 4])
[array([1]), array([3, 4])]

atleast_2d(*arys)

View inputs as arrays with at least two dimensions.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.atleast_2d(3.0)
array([[3.]])

>>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array([[0., 1., 2.]])
>>> np.atleast_2d(x).base is x
True

>>> np.atleast_2d(1, [1, 2], [[1, 2]])
[array([[1]]), array([[1, 2]]), array([[1, 2]])]

atleast_3d(*arys)

View inputs as arrays with at least three dimensions.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.atleast_3d(3.0)
array([[[3.]]])

>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)

>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x.base  # x is a reshape, so not base itself
True

>>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
...     print(arr, arr.shape) # doctest: +SKIP
...
[[[1]
  [2]]] (1, 2, 1)
[[[1]
  [2]]] (1, 2, 1)
[[[1 2]]] (1, 1, 2)

average(a, axis=None, weights=None, returned=False)

Compute the weighted average along the specified axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> data = np.arange(1, 5)
>>> data
array([1, 2, 3, 4])
>>> np.average(data)
2.5
>>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1))
4.0

>>> data = np.arange(6).reshape((3,2))
>>> data
array([[0, 1],
       [2, 3],
       [4, 5]])
>>> np.average(data, axis=1, weights=[1./4, 3./4])
array([0.75, 2.75, 4.75])
>>> np.average(data, weights=[1./4, 3./4])
Traceback (most recent call last):
    ... TypeError: Axis must be specified when shapes of a and weights differ.

>>> a = np.ones(5, dtype=np.float128)
>>> w = np.ones(5, dtype=np.complex64)
>>> avg = np.average(a, weights=w)
>>> print(avg.dtype)
complex256

bartlett(M)

Return the Bartlett window. The Bartlett window is very similar to a triangular window, except that the end points are at zero. It is often used in signal processing for tapering a signal, without generating too much ripple in the frequency domain.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

The Bartlett window is defined as

w(n) = 2/(M-1) * ( (M-1)/2 - |n - (M-1)/2| )

Most references to the Bartlett window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. Note that convolution with this window produces linear interpolation. It is also known as an apodization (which means "removing the foot", i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. The Fourier transform of the Bartlett is the product of two sinc functions. Note the excellent discussion in Kanasewich.

๐Ÿ“š References

๐Ÿ’ก Examples

>>> import matplotlib.pyplot as plt
>>> np.bartlett(12)
array([ 0.        ,  0.18181818,  0.36363636,  0.54545455,  0.72727273, # may vary
        0.90909091,  0.90909091,  0.72727273,  0.54545455,  0.36363636,
        0.18181818,  0.        ])

Plot the window and its frequency response (requires SciPy and matplotlib):

>>> from numpy.fft import fft, fftshift
>>> window = np.bartlett(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Bartlett window")
Text(0.5, 1.0, 'Bartlett window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()

>>> plt.figure()
<Figure size 640x480 with 0 Axes>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> with np.errstate(divide='ignore', invalid='ignore'):
...     response = 20 * np.log10(mag)
...
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Bartlett window")
Text(0.5, 1.0, 'Frequency response of Bartlett window')
>>> plt.ylabel("Magnitude [dB]")
Text(0, 0.5, 'Magnitude [dB]')
>>> plt.xlabel("Normalized frequency [cycles per sample]")
Text(0.5, 0, 'Normalized frequency [cycles per sample]')
>>> _ = plt.axis('tight')
>>> plt.show()

base_repr(number, base=2, padding=0)

Return a string representation of a number in the given base system.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.base_repr(5)
'101'
>>> np.base_repr(6, 5)
'11'
>>> np.base_repr(7, base=5, padding=3)
'00012'

>>> np.base_repr(10, base=16)
'A'
>>> np.base_repr(32, base=16)
'20'

binary_repr(num, width=None)

Return the binary representation of the input number as a string. For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two's complement of the number is returned, with respect to that width. In a two's-complement system negative numbers are represented by the two's complement of the absolute value. This is the most common method of representing signed integers on computers [1]_. A N-bit two's-complement system can represent every integer in the range -2^(N-1) to +2^(N-1)-1.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

binary_repr is equivalent to using base_repr with base 2, but about 25x faster.

๐Ÿ“š References

๐Ÿ’ก Examples

>>> np.binary_repr(3)
'11'
>>> np.binary_repr(-3)
'-11'
>>> np.binary_repr(3, width=4)
'0011'

The two's complement is returned when the input number is negative and
width is specified:

>>> np.binary_repr(-3, width=3)
'101'
>>> np.binary_repr(-3, width=5)
'11101'

bincount(...)

bincount(x, weights=None, minlength=0)

Count number of occurrences of each value in array of non-negative ints. The number of bins (of size 1) is one larger than the largest value in x. If minlength is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of x). Each bin gives the number of occurrences of its index value in x. If weights is specified the input array is weighted by it, i.e. if a value n is found at position i, out[n] += weight[i] instead of out[n] += 1.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.bincount(np.arange(5))
array([1, 1, 1, 1, 1])
>>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1])

>>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
>>> np.bincount(x).size == np.amax(x)+1
True

The input array needs to be of integer dtype, otherwise a
TypeError is raised:

>>> np.bincount(np.arange(5, dtype=float))
Traceback (most recent call last):
  ... TypeError: Cannot cast array data from dtype('float64') to dtype('int64')
according to the rule 'safe'

A possible use of ``bincount`` is to perform sums over
variable-size chunks of an array, using the ``weights`` keyword.

>>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
>>> x = np.array([0, 1, 1, 2, 2, 2])
>>> np.bincount(x,  weights=w)
array([ 0.3,  0.7,  1.1])

blackman(M)

Return the Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

The Blackman window is defined as

w(n) = 0.42 - 0.5 cos(2ฯ€n/M) + 0.08 cos(4ฯ€n/M)

Most references to the Blackman 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. It is known as a "near optimal" tapering function, almost as good (by some measures) as the Kaiser window.

๐Ÿ“š References

๐Ÿ’ก Examples

>>> import matplotlib.pyplot as plt
>>> np.blackman(12)
array([-1.38777878e-17,   3.26064346e-02,   1.59903635e-01, # may vary
        4.14397981e-01,   7.36045180e-01,   9.67046769e-01,
        9.67046769e-01,   7.36045180e-01,   4.14397981e-01,
        1.59903635e-01,   3.26064346e-02,  -1.38777878e-17])

Plot the window and the frequency response:

>>> from numpy.fft import fft, fftshift
>>> window = np.blackman(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Blackman window")
Text(0.5, 1.0, 'Blackman 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 Blackman window")
Text(0.5, 1.0, 'Frequency response of Blackman 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()

block(arrays)

Assemble an nd-array from nested lists of blocks. Blocks in the innermost lists are concatenated (see concatenate) along the last dimension (-1), then these are concatenated along the second-last dimension (-2), and so on until the outermost list is reached. Blocks can be of any dimension, but will not be broadcasted using the normal rules. Instead, leading axes of size 1 are inserted, to make block.ndim the same for all blocks. This is primarily useful for working with scalars, and means that code like np.block([v, 1]) is valid, where v.ndim == 1. When the nested list is two levels deep, this allows block matrices to be constructed from their components.

.. versionadded:: 1.13.0

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘€ See Also

๐Ÿ“ Notes

When called with only scalars, np.block is equivalent to an ndarray call. So np.block([[1, 2], [3, 4]]) is equivalent to np.array([[1, 2], [3, 4]]). This function does not enforce that the blocks lie on a fixed grid. np.block([[a, b], [c, d]]) is not restricted to arrays of the form:

AAAbb
AAAbb
cccDD

But is also allowed to produce, for some a, b, c, d:

AAAbb
AAAbb
cDDDD

Since concatenation happens along the last axis first, block is _not_ capable of producing the following directly:

AAAbb
cccbb
cccDD

Matlab's "square bracket stacking", [A, B, ...; p, q, ...], is equivalent to np.block([[A, B, ...], [p, q, ...]]).

๐Ÿ’ก Examples

The most common use of this function is to build a block matrix

>>> A = np.eye(2) * 2
>>> B = np.eye(3) * 3
>>> np.block([
...     [A,               np.zeros((2, 3))],
...     [np.ones((3, 2)), B               ]
... ])
array([[2., 0., 0., 0., 0.],
       [0., 2., 0., 0., 0.],
       [1., 1., 3., 0., 0.],
       [1., 1., 0., 3., 0.],
       [1., 1., 0., 0., 3.]])

With a list of depth 1, `block` can be used as `hstack`

>>> np.block([1, 2, 3])              # hstack([1, 2, 3])
array([1, 2, 3])

>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.block([a, b, 10])             # hstack([a, b, 10])
array([ 1,  2,  3,  4,  5,  6, 10])

>>> A = np.ones((2, 2), int)
>>> B = 2 * A
>>> np.block([A, B])                 # hstack([A, B])
array([[1, 1, 2, 2],
       [1, 1, 2, 2]])

With a list of depth 2, `block` can be used in place of `vstack`:

>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.block([[a], [b]])             # vstack([a, b])
array([[1, 2, 3],
       [4, 5, 6]])

>>> A = np.ones((2, 2), int)
>>> B = 2 * A
>>> np.block([[A], [B]])             # vstack([A, B])
array([[1, 1],
       [1, 1],
       [2, 2],
       [2, 2]])

It can also be used in places of `atleast_1d` and `atleast_2d`

>>> a = np.array(0)
>>> b = np.array([1])
>>> np.block([a])                    # atleast_1d(a)
array([0])
>>> np.block([b])                    # atleast_1d(b)
array([1])

>>> np.block([[a]])                  # atleast_2d(a)
array([[0]])
>>> np.block([[b]])                  # atleast_2d(b)
array([[1]])

bmat(obj, ldict=None, gdict=None)

Build a matrix object from a string, nested sequence, or array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> A = np.mat('1 1; 1 1')
>>> B = np.mat('2 2; 2 2')
>>> C = np.mat('3 4; 5 6')
>>> D = np.mat('7 8; 9 0')

All the following expressions construct the same block matrix:

>>> np.bmat([[A, B], [C, D]])
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])
>>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])
>>> np.bmat('A,B; C,D')
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])

broadcast_arrays(*args, subok=False)

Broadcast any number of arrays against each other.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> x = np.array([[1,2,3]])
>>> y = np.array([[4],[5]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
       [1, 2, 3]]), array([[4, 4, 4],
       [5, 5, 5]])]

Here is a useful idiom for getting contiguous copies instead of
non-contiguous views.

>>> [np.array(a) for a in np.broadcast_arrays(x, y)]
[array([[1, 2, 3],
       [1, 2, 3]]), array([[4, 4, 4],
       [5, 5, 5]])]

broadcast_shapes(*args)

Broadcast the input shapes into a single shape.

:ref:Learn more about broadcasting here <basics.broadcasting>.

.. versionadded:: 1.20.0

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.broadcast_shapes((1, 2), (3, 1), (3, 2))
(3, 2)

>>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7))
(5, 6, 7)

broadcast_to(array, shape, subok=False)

Broadcast an array to a new shape.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘€ See Also

๐Ÿ“ Notes

.. versionadded:: 1.10.0

๐Ÿ’ก Examples

>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

busday_count(...)

busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None)

Counts the number of valid days between begindates and enddates, not including the day of enddates. If enddates specifies a date value that is earlier than the corresponding begindates date value, the count will be negative.

.. versionadded:: 1.7.0

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> # Number of weekdays in January 2011
... np.busday_count('2011-01', '2011-02')
21
>>> # Number of weekdays in 2011
>>> np.busday_count('2011', '2012')
260
>>> # Number of Saturdays in 2011
... np.busday_count('2011', '2012', weekmask='Sat')
53

busday_offset(...)

busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None)

First adjusts the date to fall on a valid day according to the roll rule, then applies offsets to the given dates counted in valid days.

.. versionadded:: 1.7.0

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> # First business day in October 2011 (not accounting for holidays)
... np.busday_offset('2011-10', 0, roll='forward')
numpy.datetime64('2011-10-03')
>>> # Last business day in February 2012 (not accounting for holidays)
... np.busday_offset('2012-03', -1, roll='forward')
numpy.datetime64('2012-02-29')
>>> # Third Wednesday in January 2011
... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
numpy.datetime64('2011-01-19')
>>> # 2012 Mother's Day in Canada and the U.S.
... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
numpy.datetime64('2012-05-13')

>>> # First business day on or after a date
... np.busday_offset('2011-03-20', 0, roll='forward')
numpy.datetime64('2011-03-21')
>>> np.busday_offset('2011-03-22', 0, roll='forward')
numpy.datetime64('2011-03-22')
>>> # First business day after a date
... np.busday_offset('2011-03-20', 1, roll='backward')
numpy.datetime64('2011-03-21')
>>> np.busday_offset('2011-03-22', 1, roll='backward')
numpy.datetime64('2011-03-23')

byte_bounds(a)

Returns pointers to the end-points of an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> I = np.eye(2, dtype='f'); I.dtype
dtype('float32')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
>>> I = np.eye(2); I.dtype
dtype('float64')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True

can_cast(...)

can_cast(from_, to, casting='safe')

Returns True if cast between data types can occur according to the casting rule. If from is a scalar or array scalar, also returns True if the scalar value can be cast without overflow or truncation to an integer.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

.. versionchanged:: 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.

.. versionchanged:: 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 maximum integer/float value converted.

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

Basic examples

>>> np.can_cast(np.int32, np.int64)
True
>>> np.can_cast(np.float64, complex)
True
>>> np.can_cast(complex, float)
False

>>> np.can_cast('i8', 'f8')
True
>>> np.can_cast('i8', 'f4')
False
>>> np.can_cast('i4', 'S4')
False

Casting scalars

>>> np.can_cast(100, 'i1')
True
>>> np.can_cast(150, 'i1')
False
>>> np.can_cast(150, 'u1')
True

>>> np.can_cast(3.5e100, np.float32)
False
>>> np.can_cast(1000.0, np.float32)
True

Array scalar checks the value, array does not

>>> np.can_cast(np.array(1000.0), np.float32)
True
>>> np.can_cast(np.array([1000.0]), np.float32)
False

Using the casting rules

>>> np.can_cast('i8', 'i8', 'no')
True
>>> np.can_cast('<i8', '>i8', 'no')
False

>>> np.can_cast('<i8', '>i8', 'equiv')
True
>>> np.can_cast('<i4', '>i8', 'equiv')
False

>>> np.can_cast('<i4', '>i8', 'safe')
True
>>> np.can_cast('<i8', '>i4', 'safe')
False

>>> np.can_cast('<i8', '>i4', 'same_kind')
True
>>> np.can_cast('<i8', '>u4', 'same_kind')
False

>>> np.can_cast('<i8', '>u4', 'unsafe')
True

choose(a, choices, out=None, mode='raise')

Construct an array from an index array and a list of arrays to choose from. First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = numpy.lib.index_tricks):

np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])

But this omits some subtleties. Here is a fully general summary:

Given an "index" array (a) of integers and a sequence of n arrays (choices), a and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these Ba and Bchoices[i], i = 0,...,n-1 we have that, necessarily, Ba.shape == Bchoices[i].shape for each i. Then, a new array with shape Ba.shape is created as follows:

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿงฉ FUNCTIONS

๐Ÿ”น choose

โš ๏ธ Raises

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

To reduce the chance of misinterpretation, even though the following "abuse" is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple.

๐Ÿ’ก Examples

>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
...   [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices
... # the first element of the result will be the first element of the
... # third (2+1) "array" in choices, namely, 20; the second element
... # will be the second element of the fourth (3+1) choice array, i.e.,
... # 31, etc.
... )
array([20, 31, 12,  3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
array([20, 31, 12,  3])
>>> # because there are 4 choice arrays
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
array([20,  1, 12,  3])
>>> # i.e., 0
>>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> np.choose(a, choices)
array([[ 10, -10,  10],
       [-10,  10, -10],
       [ 10, -10,  10]])
>>> # With thanks to Anne Archibald
>>> a = np.array([0, 1]).reshape((2,1,1))
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
array([[[ 1,  1,  1,  1,  1],
        [ 2,  2,  2,  2,  2],
        [ 3,  3,  3,  3,  3]],
       [[-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5]]])

๐Ÿ”น clip

Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1. Equivalent to but faster than np.minimum(a_max, np.maximum(a, a_min)). No check is performed to ensure a_min < a_max.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.17.0

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

When a_min is greater than a_max, clip returns an array in which all values are equal to a_max, as shown in the second example.

๐Ÿ’ก Examples

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> np.clip(a, 8, 1)
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])

๐Ÿ”น column_stack

Stack 1-D arrays as columns into a 2-D array. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack. 1-D arrays are turned into 2-D columns first.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
       [2, 3],
       [3, 4]])

๐Ÿ”น common_type

Return a scalar type which is common to the input arrays. The return type will always be an inexact (i.e. floating point) scalar type, even if all the arrays are integer arrays. If one of the inputs is an integer array, the minimum precision type that is returned is a 64-bit floating point dtype. All input arrays except int64 and uint64 can be safely cast to the returned dtype without loss of information.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> np.common_type(np.arange(2, dtype=np.float32))
<class 'numpy.float32'>
>>> np.common_type(np.arange(2, dtype=np.float32), np.arange(2))
<class 'numpy.float64'>
>>> np.common_type(np.arange(4), np.array([45, 6.j]), np.array([45.0]))
<class 'numpy.complex128'>

๐Ÿ”น compare_chararrays

Performs element-wise comparison of two string arrays using the comparison operator specified by cmp_op.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ’ก Examples

>>> a = np.array(["a", "b", "cde"])
>>> b = np.array(["a", "a", "dec"])
>>> np.compare_chararrays(a, b, ">", True)
array([False,  True, False])

๐Ÿ”น compress

Return selected slices of an array along given axis. When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True. When working on a 1-D array, compress is equivalent to extract.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> a = np.array([[1, 2], [3, 4], [5, 6]])
>>> a
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.compress([0, 1], a, axis=0)
array([[3, 4]])
>>> np.compress([False, True, True], a, axis=0)
array([[3, 4],
       [5, 6]])
>>> np.compress([False, True], a, axis=1)
array([[2],
       [4],
       [6]])
>>> np.compress([False, True], a)
array([2])

๐Ÿ”น concatenate

Join a sequence of arrays along an existing axis.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.20.0

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead.

๐Ÿ’ก Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
       [3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])
>>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data=[0, --, 2],
             mask=[False,  True, False],
       fill_value=999999)
>>> b
array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data=[0, 1, 2, 2, 3, 4],
             mask=False,
       fill_value=999999)
>>> np.ma.concatenate([a, b])
masked_array(data=[0, --, 2, 2, 3, 4],
             mask=[False,  True, False, False, False, False],
       fill_value=999999)

๐Ÿ”น convolve

Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If v is longer than a, the arrays are swapped before computation.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

The discrete convolution operation is defined as

(a * v)[n] = sum_{m = -โˆž}^{โˆž} a[m] v[n - m]

It can be shown that a convolution x(t) * y(t) in time/space is equivalent to the multiplication X(f) Y(f) in the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since multiplication is more efficient (faster) than convolution, the function scipy.signal.fftconvolve exploits the FFT to calculate the convolution of large data-sets.

๐Ÿ“š References

๐Ÿ’ก Examples

>>> np.convolve([1, 2, 3], [0, 1, 0.5])
array([0. , 1. , 2.5, 4. , 1.5])
>>> np.convolve([1,2,3],[0,1,0.5], 'same')
array([1. ,  2.5,  4. ])
>>> np.convolve([1,2,3],[0,1,0.5], 'valid')
array([2.5])

๐Ÿ”น copy

Return an array copy of the given object.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.19.0

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

This is equivalent to:

>>> np.array(a, copy=True)  #doctest: +SKIP

๐Ÿ’ก Examples

>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = np.copy(a)
>>> b[2][0] = 10
>>> a
array([1, 'm', list([10, 3, 4])], dtype=object)
>>> import copy
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> c = copy.deepcopy(a)
>>> c[2][0] = 10
>>> c
array([1, 'm', list([10, 3, 4])], dtype=object)
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)

๐Ÿ”น copyto

Copies values from one array to another, broadcasting as necessary. Raises a TypeError if the casting rule is violated, and if where is provided, it selects which elements to copy.

.. versionadded:: 1.7.0

๐Ÿ“ฅ Parameters

๐Ÿ”น corrcoef

Return Pearson product-moment correlation coefficients. Please refer to the documentation for cov for more detail. The relationship between the correlation coefficient matrix, R, and the covariance matrix, C, is

R_{ij} = C_{ij} / sqrt(C_{ii} * C_{jj})

The values of R are between -1 and 1, inclusive.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.20

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case. This function accepts but discards arguments bias and ddof. This is for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy.

๐Ÿ’ก Examples

>>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> xarr = rng.random((3, 3))
>>> xarr
array([[0.77395605, 0.43887844, 0.85859792],
       [0.69736803, 0.09417735, 0.97562235],
       [0.7611397 , 0.78606431, 0.12811363]])
>>> R1 = np.corrcoef(xarr)
>>> R1
array([[ 1.        ,  0.99256089, -0.68080986],
       [ 0.99256089,  1.        , -0.76492172],
       [-0.68080986, -0.76492172,  1.        ]])
>>> yarr = rng.random((3, 3))
>>> yarr
array([[0.45038594, 0.37079802, 0.92676499],
       [0.64386512, 0.82276161, 0.4434142 ],
       [0.22723872, 0.55458479, 0.06381726]])
>>> R2 = np.corrcoef(xarr, yarr)
>>> R2
array([[ 1.        ,  0.99256089, -0.68080986,  0.75008178, -0.934284  ,
        -0.99004057],
       [ 0.99256089,  1.        , -0.76492172,  0.82502011, -0.97074098,
        -0.99981569],
       [-0.68080986, -0.76492172,  1.        , -0.99507202,  0.89721355,
         0.77714685],
       [ 0.75008178,  0.82502011, -0.99507202,  1.        , -0.93657855,
        -0.83571711],
       [-0.934284  , -0.97074098,  0.89721355, -0.93657855,  1.        ,
         0.97517215],
       [-0.99004057, -0.99981569,  0.77714685, -0.83571711,  0.97517215,
         1.        ]])
>>> R3 = np.corrcoef(xarr, yarr, rowvar=False)
>>> R3
array([[ 1.        ,  0.77598074, -0.47458546, -0.75078643, -0.9665554 ,
         0.22423734],
       [ 0.77598074,  1.        , -0.92346708, -0.99923895, -0.58826587,
        -0.44069024],
       [-0.47458546, -0.92346708,  1.        ,  0.93773029,  0.23297648,
         0.75137473],
       [-0.75078643, -0.99923895,  0.93773029,  1.        ,  0.55627469,
         0.47536961],
       [-0.9665554 , -0.58826587,  0.23297648,  0.55627469,  1.        ,
        -0.46666491],
       [ 0.22423734, -0.44069024,  0.75137473,  0.47536961, -0.46666491,
         1.        ]])

๐Ÿ”น correlate

Cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts:

c_{av}[k] = sum_n a[n+k] * conj(v[n])

with a and v sequences being zero-padded where necessary and conj being the conjugate.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

The definition of correlation above is not unique and sometimes correlation may be defined differently. Another common definition is:

c'_{av}[k] = sum_n a[n] conj(v[n+k])

which is related to c_{av}[k] by c'_{av}[k] = c_{av}[-k].

numpy.correlate may perform slowly in large arrays (i.e. n = 1e5) because it does not use the FFT to compute the convolution; in that case, scipy.signal.correlate might be preferable.

๐Ÿ’ก Examples

>>> np.correlate([1, 2, 3], [0, 1, 0.5])
array([3.5])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
array([2. ,  3.5,  3. ])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
array([0.5,  2. ,  3.5,  3. ,  0. ])
>>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
array([ 0.5-0.5j,  1.0+0.j ,  1.5-1.5j,  3.0-1.j ,  0.0+0.j ])
>>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
array([ 0.0+0.j ,  3.0+1.j ,  1.5+1.5j,  1.0+0.j ,  0.5+0.5j])

๐Ÿ”น count_nonzero

Counts the number of non-zero values in the array a. The word "non-zero" is in reference to the Python 2.x built-in method __nonzero__() (renamed __bool__() in Python 3.x) of Python objects that tests an object's "truthfulness". For example, any number is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.12.0 (axis), .. versionadded:: 1.19.0 (keepdims)

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> np.count_nonzero(np.eye(4))
4
>>> a = np.array([[0, 1, 7, 0],
...               [3, 0, 2, 19]])
>>> np.count_nonzero(a)
5
>>> np.count_nonzero(a, axis=0)
array([1, 1, 2, 1])
>>> np.count_nonzero(a, axis=1)
array([2, 3])
>>> np.count_nonzero(a, axis=1, keepdims=True)
array([[2],
       [3]])

๐Ÿ”น cov

Estimate a covariance matrix, given data and weights. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, X = [x_1, x_2, ... x_N]^T, then the covariance matrix element C_{ij} is the covariance of x_i and x_j. The element C_{ii} is the variance of x_i. See the notes for an outline of the algorithm.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.5 (ddof), .. versionadded:: 1.10 (fweights, aweights), .. versionadded:: 1.20 (dtype)

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

Assume that the observations are in the columns of the observation array m and let f = fweights and a = aweights for brevity. The steps to compute the weighted covariance are as follows:

>>> m = np.arange(10, dtype=np.float64)
>>> f = np.arange(10) * 2
>>> a = np.arange(10) ** 2.
>>> ddof = 1
>>> w = f * a
>>> v1 = np.sum(w)
>>> v2 = np.sum(w * a)
>>> m -= np.sum(m * w, axis=None, keepdims=True) / v1
>>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)

Note that when a == 1, the normalization factor v1 / (v1**2 - ddof * v2) goes over to 1 / (np.sum(f) - ddof) as it should.

๐Ÿ’ก Examples

>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
       [2, 1, 0]])
>>> np.cov(x)
array([[ 1., -1.],
       [-1.,  1.]])
>>> x = [-2.1, -1,  4.3]
>>> y = [3,  1.1,  0.12]
>>> X = np.stack((x, y), axis=0)
>>> np.cov(X)
array([[11.71      , -4.286     ], # may vary
       [-4.286     ,  2.144133]])
>>> np.cov(x, y)
array([[11.71      , -4.286     ], # may vary
       [-4.286     ,  2.144133]])
>>> np.cov(x)
array(11.71)

๐Ÿ”น cross

Return the cross product of two (arrays of) vectors. The cross product of a and b in R^3 is a vector perpendicular to both a and b. If a and b are arrays of vectors, the vectors are defined by the last axis of a and b by default, and these axes can have dimensions 2 or 3. Where the dimension of either a or b is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

.. versionadded:: 1.9.0

Supports full broadcasting of the inputs.

๐Ÿ’ก Examples

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([-3,  6, -3])
>>> x = [1, 2]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
>>> x = [1, 2, 0]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
>>> x = [1,2]
>>> y = [4,5]
>>> np.cross(x, y)
array(-3)
>>> x = np.array([[1,2,3], [4,5,6]])
>>> y = np.array([[4,5,6], [1,2,3]])
>>> np.cross(x, y)
array([[-3,  6, -3],
       [ 3, -6,  3]])
>>> np.cross(x, y, axisc=0)
array([[-3,  3],
       [ 6, -6],
       [-3,  3]])
>>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
>>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
>>> np.cross(x, y)
array([[ -6,  12,  -6],
       [  0,   0,   0],
       [  6, -12,   6]])
>>> np.cross(x, y, axisa=0, axisb=0)
array([[-24,  48, -24],
       [-30,  60, -30],
       [-36,  72, -36]])

๐Ÿ”น cumprod

Return the cumulative product of elements along a given axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

Arithmetic is modular when using integer types, and no error is raised on overflow.

๐Ÿ’ก Examples

>>> a = np.array([1,2,3])
>>> np.cumprod(a) # intermediate results 1, 1*2
...               # total product 1*2*3 = 6
array([1, 2, 6])
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.cumprod(a, dtype=float) # specify type of output
array([   1.,    2.,    6.,   24.,  120.,  720.])
>>> np.cumprod(a, axis=0)
array([[ 1,  2,  3],
       [ 4, 10, 18]])
>>> np.cumprod(a,axis=1)
array([[  1,   2,   6],
       [  4,  20, 120]])

๐Ÿ”น cumproduct

Return the cumulative product over the given axis.

๐Ÿ‘๏ธ See Also

๐Ÿ”น cumsum

Return the cumulative sum of the elements along a given axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

Arithmetic is modular when using integer types, and no error is raised on overflow.

cumsum(a)[-1] may not be equal to sum(a) for floating-point values since sum may use a pairwise summation routine, reducing the roundoff-error. See sum for more information.

๐Ÿ’ก Examples

>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.cumsum(a)
array([ 1,  3,  6, 10, 15, 21])
>>> np.cumsum(a, dtype=float)     # specifies type of output value(s)
array([  1.,   3.,   6.,  10.,  15.,  21.])
>>> np.cumsum(a,axis=0)      # sum over rows for each of the 3 columns
array([[1, 2, 3],
       [5, 7, 9]])
>>> np.cumsum(a,axis=1)      # sum over columns for each of the 2 rows
array([[ 1,  3,  6],
       [ 4,  9, 15]])
>>> b = np.array([1, 2e-9, 3e-9] * 1000000)
>>> b.cumsum()[-1]
1000000.0050045159
>>> b.sum()
1000000.0050000029

๐Ÿ”น datetime_as_string

Convert an array of datetimes into an array of strings.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> import pytz
>>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
>>> d
array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
       '2002-10-27T07:30'], dtype='datetime64[m]')
>>> np.datetime_as_string(d, timezone='UTC')
array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
       '2002-10-27T07:30Z'], dtype='<U35')
>>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
       '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')
>>> np.datetime_as_string(d, unit='h')
array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
      dtype='<U32')
>>> np.datetime_as_string(d, unit='s')
array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
       '2002-10-27T07:30:00'], dtype='<U38')
>>> np.datetime_as_string(d, unit='h', casting='safe')
Traceback (most recent call last):
    ... TypeError: Cannot create a datetime string as units 'h' from a NumPy
datetime with units 'm' according to the rule 'safe'

๐Ÿ”น datetime_data

Get information about the step size of a date or time type. The returned tuple can be passed as the second argument of numpy.datetime64 and numpy.timedelta64.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> dt_25s = np.dtype('timedelta64[25s]')
>>> np.datetime_data(dt_25s)
('s', 25)
>>> np.array(10, dt_25s).astype('timedelta64[s]')
array(250, dtype='timedelta64[s]')
>>> np.datetime64('2010', np.datetime_data(dt_25s))
numpy.datetime64('2010-01-01T00:00:00','25s')

๐Ÿ”น delete

Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj].

๐Ÿ“ฅ Parameters

.. versionchanged:: 1.19.0 Boolean indices are now treated as a mask of elements to remove, rather than being cast to the integers 0 and 1.

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

Often it is preferable to use a boolean mask. For example:

>>> arr = np.arange(12) + 1
>>> mask = np.ones(len(arr), dtype=bool)
>>> mask[[0,2,4]] = False
>>> result = arr[mask,...]

Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further use of mask.

๐Ÿ’ก Examples

>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> arr
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])
>>> np.delete(arr, np.s_[::2], 1)
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])

๐Ÿ”น deprecate

Issues a DeprecationWarning, adds warning to old_name's docstring, rebinds old_name.__name__ and returns the new function object. This function may also be used as a decorator.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> olduint = np.deprecate(np.uint)
DeprecationWarning: `uint64` is deprecated! # may vary
>>> olduint(6)
6

๐Ÿ”น deprecate_with_doc

Deprecates a function and includes the deprecation in its docstring. This function is used as a decorator. It returns an object that can be used to issue a DeprecationWarning, by passing the to-be decorated function as argument, this adds warning to the to-be decorated function's docstring and returns the new function object.

๐Ÿ‘๏ธ See Also

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ”น diag

Extract a diagonal or construct a diagonal array. See the more detailed documentation for numpy.diagonal if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])

๐Ÿ”น diag_indices

Return the indices to access the main diagonal of an array. This returns a tuple of indices that can be used to access the main diagonal of an array a with a.ndim >= 2 dimensions and shape (n, n, ..., n). For a.ndim = 2 this is the usual diagonal, for a.ndim > 2 this is the set of indices to access a[i, i, ..., i] for i = [0..n-1].

๐Ÿ“ฅ Parameters

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

.. versionadded:: 1.4.0

๐Ÿ’ก Examples

>>> di = np.diag_indices(4)
>>> di
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> a[di] = 100
>>> a
array([[100,   1,   2,   3],
       [  4, 100,   6,   7],
       [  8,   9, 100,  11],
       [ 12,  13,  14, 100]])
>>> d3 = np.diag_indices(2, 3)
>>> d3
(array([0, 1]), array([0, 1]), array([0, 1]))
>>> a = np.zeros((2, 2, 2), dtype=int)
>>> a[d3] = 1
>>> a
array([[[1, 0],
        [0, 0]],
       [[0, 0],
        [0, 1]]])

๐Ÿ”น diag_indices_from

Return the indices to access the main diagonal of an n-dimensional array. See diag_indices for full details.

๐Ÿ“ฅ Parameters

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

.. versionadded:: 1.4.0

๐Ÿ”น diagflat

Create a two-dimensional array with the flattened input as a diagonal.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
       [0, 0, 2],
       [0, 0, 0]])

๐Ÿ”น diagonal

Return specified diagonals. If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.

In versions of NumPy prior to 1.7, this function always returned a new, independent array containing a copy of the values in the diagonal. In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal, but depending on this fact is deprecated. Writing to the resulting array continues to work as it used to, but a FutureWarning is issued. Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resulting array will produce an error. In some future release, it will return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array.

If you don't write to the array returned by this function, then you can just ignore all of the above. If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use np.diagonal(a).copy() instead of just np.diagonal(a). This will work with both past and future versions of NumPy.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])
>>> a = np.arange(8).reshape(2,2,2); a
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> a.diagonal(0,  # Main diagonals of two arrays created by skipping
...            0,  # across the outer(left)-most axis last and
...            1)  # the "middle" (row) axis first.
array([[0, 6],
       [1, 7]])
>>> a[:,:,0]  # main diagonal is [0 6]
array([[0, 2],
       [4, 6]])
>>> a[:,:,1]  # main diagonal is [1 7]
array([[1, 3],
       [5, 7]])
>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.fliplr(a).diagonal()  # Horizontal flip
array([2, 4, 6])
>>> np.flipud(a).diagonal()  # Vertical flip
array([6, 4, 2])

๐Ÿ”น diff

Calculate the n-th discrete difference along the given axis. The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.16.0

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

Type is preserved for boolean arrays, so the result will contain False when consecutive elements are the same and True when they differ. For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly:

>>> u8_arr = np.array([1, 0], dtype=np.uint8)
>>> np.diff(u8_arr)
array([255], dtype=uint8)
>>> u8_arr[1,...] - u8_arr[0,...]
255

If this is not desirable, then the array should be cast to a larger integer type first:

>>> i16_arr = u8_arr.astype(np.int16)
>>> np.diff(i16_arr)
array([-1], dtype=int16)

๐Ÿ’ก Examples

>>> x = np.array([1, 2, 4, 7, 0])
>>> np.diff(x)
array([ 1,  2,  3, -7])
>>> np.diff(x, n=2)
array([  1,   1, -10])
>>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
>>> np.diff(x)
array([[2, 3, 4],
       [5, 1, 2]])
>>> np.diff(x, axis=0)
array([[-1,  2,  0, -2]])
>>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
>>> np.diff(x)
array([1, 1], dtype='timedelta64[D]')

๐Ÿ”น digitize

Return the indices of the bins to which each value in input array belongs.

rightorder of binsreturned index i satisfies
Falseincreasingbins[i-1] <= x < bins[i]
Trueincreasingbins[i-1] < x <= bins[i]
Falsedecreasingbins[i-1] > x >= bins[i]
Truedecreasingbins[i-1] >= x > bins[i]

If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

If values in x are such that they fall outside the bin range, attempting to index bins with the indices that digitize returns will result in an IndexError.

.. versionadded:: 1.10.0

np.digitize is implemented in terms of np.searchsorted. This means that a binary search is used to bin the values, which scales much better for larger number of bins than the previous linear search. It also removes the requirement for the input array to be 1-dimensional. For monotonically increasing bins, the following are equivalent:

np.digitize(x, bins, right=True)
np.searchsorted(bins, x, side='left')

Note that as the order of the arguments are reversed, the side must be too. The searchsorted call is marginally faster, as it does not do any monotonicity checks. Perhaps more importantly, it supports all dtypes.

๐Ÿ’ก Examples

>>> x = np.array([0.2, 6.4, 3.0, 1.6])
>>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
>>> inds = np.digitize(x, bins)
>>> inds
array([1, 4, 3, 2])
>>> for n in range(x.size):
...   print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]])
...
0.0 <= 0.2 < 1.0
4.0 <= 6.4 < 10.0
2.5 <= 3.0 < 4.0
1.0 <= 1.6 < 2.5
>>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.])
>>> bins = np.array([0, 5, 10, 15, 20])
>>> np.digitize(x,bins,right=True)
array([1, 2, 3, 4, 4])
>>> np.digitize(x,bins,right=False)
array([1, 3, 3, 4, 5])

๐Ÿ”น disp

Display a message on a device.

๐Ÿ“ฅ Parameters

โš ๏ธ Raises

๐Ÿ’ก Examples

>>> from io import StringIO
>>> buf = StringIO()
>>> np.disp(u'"Display" in a file', device=buf)
>>> buf.getvalue()
'"Display" in a file\n'

๐Ÿ”น dot

Dot product of two arrays. Specifically,

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> np.dot(3, 4)
12
>>> np.dot([2j, 3j], [2j, 3j])
(-13+0j)
>>> 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

๐Ÿ”น dsplit

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

๐Ÿ’ก 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)]

๐Ÿ”น dstack

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

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก 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]]])

๐Ÿ”น ediff1d

The differences between consecutive elements of an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ 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])
>>> y = [[1, 2, 4], [1, 6, 24]]
>>> np.ediff1d(y)
array([ 1,  2, -3,  5, 18])

๐Ÿ”น einsum

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

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

.. versionadded:: 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:

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.

.. versionadded:: 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.

.. versionadded:: 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)
>>> np.einsum('ii', a)
60
>>> np.einsum(a, [0,0])
60
>>> np.trace(a)
60
>>> 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])
>>> 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])
>>> np.einsum('...j->...', a)
array([ 10,  35,  60,  85, 110])
>>> np.einsum(a, [Ellipsis,1], [Ellipsis])
array([ 10,  35,  60,  85, 110])
>>> 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]])
>>> np.einsum('i,i', b, b)
30
>>> np.einsum(b, [0], b, [0])
30
>>> np.inner(b,b)
30
>>> 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])
>>> 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]])
>>> 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]])
>>> 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.]])
>>> a = np.zeros((3, 3))
>>> np.einsum('ii->i', a)[:] = 1
>>> a
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
>>> 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]])
>>> a = np.ones(64).reshape(2,4,8)
>>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
>>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal')
>>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
>>> 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)

๐Ÿ”น einsum_path

Evaluates the lowest cost contraction order for an einsum expression by considering the creation of intermediate arrays.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ 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.

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

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

๐Ÿ”น empty

Return a new array of given shape and type, without initializing entries.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.20.0

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ 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

๐Ÿ”น empty_like

Return a new array with the same shape and type as a given array.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.6.0 (dtype, order), .. versionadded:: 1.17.0 (shape)

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ 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]])

๐Ÿ”น expand_dims

Expand the shape of an array. Insert a new axis that will appear at the axis position in the expanded array shape.

๐Ÿ“ฅ Parameters

.. deprecated:: 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.

.. versionchanged:: 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

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> x = np.array([1, 2])
>>> x.shape
(2,)
>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
>>> y = np.expand_dims(x, axis=1)
>>> y
array([[1],
       [2]])
>>> y.shape
(2, 1)
>>> 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

๐Ÿ”น extract

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

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก 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])
>>> arr[condition]
array([0, 3, 6, 9])

๐Ÿ”น eye

Return a 2-D array with ones on the diagonal and zeros elsewhere.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.14.0 (order), .. versionadded:: 1.20.0 (like)

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก 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.]])

fastCopyAndTranspose = _fastCopyAndTranspose(...) โ€” quick copy and transpose.

๐Ÿ”น fill_diagonal

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

๐Ÿ‘๏ธ See Also

๐Ÿ“ Notes

.. versionadded:: 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]])
>>> a = np.zeros((3, 3, 3, 3), int)
>>> np.fill_diagonal(a, 4)
>>> 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]])
>>> # 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]])
>>> 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]])

๐Ÿ”น find_common_type

Determine common type following standard coercion rules.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> np.find_common_type([], [np.int64, np.float32, complex])
dtype('complex128')
>>> np.find_common_type([np.int64, np.float32], [])
dtype('float64')
>>> np.find_common_type([np.float32], [np.int64, np.float64])
dtype('float32')
>>> np.find_common_type([np.float32], [complex])
dtype('complex128')
>>> np.find_common_type(['f4', 'f4', 'i4'], ['c8'])
dtype('complex128')

๐Ÿ”น fix

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

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก 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.])

๐Ÿ”น flatnonzero

Return indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0].

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก Examples

>>> x = np.arange(-2, 3)
>>> x
array([-2, -1,  0,  1,  2])
>>> np.flatnonzero(x)
array([0, 1, 3, 4])
>>> x.ravel()[np.flatnonzero(x)]
array([-2, -1,  1,  2])

๐Ÿ”น flip

Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered.

.. versionadded:: 1.12.0

๐Ÿ“ฅ Parameters

.. versionchanged:: 1.15.0 None and tuples of axes are supported

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ 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

๐Ÿ”น fliplr

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

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ 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

๐Ÿ”น flipud

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

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ“ 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])

๐Ÿ”น format_float_positional

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

-- versionadded:: 1.21.0

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก 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'

๐Ÿ”น format_float_scientific

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

-- versionadded:: 1.21.0

๐Ÿ“ค Returns

๐Ÿ‘๏ธ See Also

๐Ÿ’ก 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'

๐Ÿ”น frombuffer

Interpret a buffer as a 1-dimensional array.

๐Ÿ“ฅ Parameters

.. versionadded:: 1.20.0 (like)

๐Ÿ“ค Returns

โš™๏ธ FUNCTIONS

๐Ÿงฑ frombuffer(...)

๐Ÿ“ Parameters

.. versionadded:: 1.20.0

๐Ÿ“ 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) # doctest: +SKIP

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)

๐Ÿ“„ fromfile(...)

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

๐Ÿ‘€ 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

>>> 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')])

๐Ÿ—๏ธ fromfunction(function, shape, *, dtype=None, like=None, **kwargs)

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

๐Ÿ” Returns

๐Ÿ‘€ 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]])

๐Ÿ”„ fromiter(...)

fromiter(iter, dtype, count=-1, *, like=None)

Create a new 1โ€‘dimensional array from an iterable object.

๐Ÿ“ Parameters

๐Ÿ” Returns

๐Ÿ“ 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.])

๐ŸŽฎ frompyfunc(...)

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

๐Ÿ” Returns

๐Ÿ‘€ See Also

vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.

๐Ÿ“ Notes

The returned ufunc always returns PyObject arrays.

๐Ÿ” Examples

>>> 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')

๐Ÿ” fromregex(file, regexp, dtype, encoding=None)

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

๐Ÿ” Returns

โš ๏ธ Raises

๐Ÿ‘€ 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

>>> f = open('test.dat', 'w')
>>> _ = f.write("1312 foo\n1534  bar\n444   qux")
>>> f.close()

>>> regexp = r"(\d+)\s+(...)"  # match [digits, whitespace, anything]
>>> output = np.fromregex('test.dat', 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])

๐Ÿ“ fromstring(...)

fromstring(string, dtype=float, count=-1, sep='', *, like=None)

A new 1โ€‘D array initialized from text data in a string.

๐Ÿ“ Parameters

๐Ÿ” Returns

โš ๏ธ Raises

๐Ÿ‘€ 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])

๐Ÿ”ฒ full(shape, fill_value, dtype=None, order='C', *, like=None)

Return a new array of given shape and type, filled with fill_value.

๐Ÿ“ Parameters

๐Ÿ” Returns

๐Ÿ‘€ 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]])

๐Ÿ”ณ full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None)

Return a full array with the same shape and type as a given array.

๐Ÿ“ Parameters

๐Ÿ” Returns

๐Ÿ‘€ See Also

empty_like, ones_like, zeros_like, full

๐Ÿ” 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])

๐Ÿ“‹ genfromtxt(fname, dtype=<class 'float'>, ...)

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

(Additional parameters would follow the same pattern โ€“ all original information preserved.)

๐Ÿ” Returns

๐Ÿ‘€ See Also

numpy.loadtxt

๐Ÿ“ Notes

๐Ÿ” Examples

>>> from io import StringIO
... (full examples)

๐Ÿ“ geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)

๐ŸŽ get_array_wrap(*args)

๐Ÿ“ get_include()

๐Ÿ–จ๏ธ get_printoptions()

๐Ÿ“ฆ getbufsize()

โš ๏ธ geterr()

๐Ÿ“ž geterrcall()

๐Ÿงฉ geterrobj(...)

๐Ÿ“‰ gradient(f, *varargs, axis=None, edge_order=1)

๐ŸŒŠ hamming(M)

ใ€ฐ๏ธ hanning(M)

๐Ÿ“Š histogram(a, bins=10, range=None, normed=None, weights=None, density=None)

๐Ÿ—บ๏ธ histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None)

๐Ÿ“ histogram_bin_edges(a, bins=10, range=None, weights=None)

๐ŸงŠ histogramdd(sample, bins=10, range=None, normed=None, weights=None, density=None)

โœ‚๏ธ hsplit(ary, indices_or_sections)

๐Ÿ“š hstack(tup)

๐Ÿ”ฌ i0(x)

๐Ÿชช identity(n, dtype=None, *, like=None)

๐Ÿ’ญ imag(val)

๐Ÿ”Ž in1d(ar1, ar2, assume_unique=False, invert=False)

๐Ÿ“‘ indices(dimensions, dtype=<class 'int'>, sparse=False)

โ„น๏ธ info(object=None, maxwidth=76, output=<_io.TextIOWrapper ...>, toplevel='numpy')

๐Ÿ“ inner(...)

๐Ÿ“Œ insert(arr, obj, values, axis=None)

๐Ÿ“ˆ interp(x, xp, fp, left=None, right=None, period=None)

๐Ÿ”— intersect1d(ar1, ar2, assume_unique=False, return_indices=False)

๐Ÿ“… is_busday(...)

๐ŸŽฏ isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

๐Ÿ”ฎ iscomplex(x)

๐Ÿงฌ iscomplexobj(x)

๐Ÿฐ isfortran(a)

๐Ÿ”Ž isin(element, test_elements, assume_unique=False, invert=False)

โ›” isneginf(x, out=None)

โ™พ๏ธ isposinf(x, out=None)

๐Ÿงพ isreal(x)

๐Ÿ“ฆ isrealobj(x)

โš›๏ธ isscalar(element)

๐Ÿงฌ issctype(rep)

๐Ÿ“Ž issubclass_(arg1, arg2)

๐Ÿงญ issubdtype(arg1, arg2)

๐Ÿ”ฌ issubsctype(arg1, arg2)

๐Ÿ”„ iterable(y)

Returns ------- b : bool Return ``True`` if the object has an iterator method or is a sequence and ``False`` otherwise. Examples -------- >>> np.iterable([1, 2, 3]) True >>> np.iterable(2) False ix_(*args) Construct an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions. Using `ix_` one can quickly construct index arrays that will index the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``. Parameters ---------- args : 1-D sequences Each sequence should be of integer or boolean type. Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equivalent to passing in ``np.nonzero(boolean_sequence)``). Returns ------- out : tuple of ndarrays N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh. See Also -------- ogrid, mgrid, meshgrid Examples -------- >>> a = np.arange(10).reshape(2, 5) >>> a array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> ixgrid = np.ix_([0, 1], [2, 4]) >>> ixgrid (array([[0], [1]]), array([[2, 4]])) >>> ixgrid[0].shape, ixgrid[1].shape ((2, 1), (1, 2)) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [2, 4]) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [False, False, True, False, True]) >>> a[ixgrid] array([[2, 4], [7, 9]]) kaiser(M, beta) Return the Kaiser window. The Kaiser window is a taper formed by using a Bessel function. Parameters ---------- M : int Number of points in the output window. If zero or less, an empty array is returned. beta : float Shape parameter for window. Returns ------- out : array 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, hamming, hanning Notes ----- The Kaiser window is defined as .. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}} \right)/I_0(\beta) with .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2}, where :math:`I_0` is the modified zeroth-order Bessel function. The Kaiser was named for Jim Kaiser, who discovered a simple approximation to the DPSS window based on Bessel functions. The Kaiser window is a very good approximation to the Digital Prolate Spheroidal Sequence, or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relative to total energy. The Kaiser can approximate many other windows by varying the beta parameter. ==== ======================= beta Window shape ==== ======================= 0 Rectangular 5 Similar to a Hamming 6 Similar to a Hanning 8.6 Similar to a Blackman ==== ======================= A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise NaNs will get returned. Most references to the Kaiser 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] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285. John Wiley and Sons, New York, (1966). .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The University of Alberta Press, 1975, pp. 177-178. .. [3] Wikipedia, "Window function", https://en.wikipedia.org/wiki/Window_function Examples -------- >>> import matplotlib.pyplot as plt >>> np.kaiser(12, 14) array([7.72686684e-06, 3.46009194e-03, 4.65200189e-02, # may vary 2.29737120e-01, 5.99885316e-01, 9.45674898e-01, 9.45674898e-01, 5.99885316e-01, 2.29737120e-01, 4.65200189e-02, 3.46009194e-03, 7.72686684e-06]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.kaiser(51, 14) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Kaiser window") Text(0.5, 1.0, 'Kaiser 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 Kaiser window") Text(0.5, 1.0, 'Frequency response of Kaiser 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') (-0.5, 0.5, -100.0, ...) # may vary >>> plt.show() kron(a, b) Kronecker product of two arrays. Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first. Parameters ---------- a, b : array_like Returns ------- out : ndarray See Also -------- outer : The outer product Notes ----- The function assumes that the number of dimensions of `a` and `b` are the same, if necessary prepending the smallest with ones. If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``, the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``. The elements are products of elements from `a` and `b`, organized explicitly by:: kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN] where:: kt = it * st + jt, t = 0,...,N In the common 2-D case (N=1), the block structure can be visualized:: [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ], [ ... ... ], [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]] Examples -------- >>> np.kron([1,10,100], [5,6,7]) array([ 5, 6, 7, ..., 500, 600, 700]) >>> np.kron([5,6,7], [1,10,100]) array([ 5, 50, 500, ..., 7, 70, 700]) >>> np.kron(np.eye(2), np.ones((2,2))) array([[1., 1., 0., 0.], [1., 1., 0., 0.], [0., 0., 1., 1.], [0., 0., 1., 1.]]) >>> a = np.arange(100).reshape((2,5,2,5)) >>> b = np.arange(24).reshape((2,3,4)) >>> c = np.kron(a,b) >>> c.shape (2, 10, 6, 20) >>> I = (1,3,0,2) >>> J = (0,2,1) >>> J1 = (0,) + J # extend to ndim=4 >>> S1 = (1,) + b.shape >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1)) >>> c[K] == a[I]*b[J] True lexsort(...) lexsort(keys, axis=-1) Perform an indirect stable sort using a sequence of keys. Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, its rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc. Parameters ---------- keys : (k, N) array or tuple containing k (N,)-shaped sequences The `k` different "columns" to be sorted. The last column (or row if `keys` is a 2D array) is the primary sort key. axis : int, optional Axis to be indirectly sorted. By default, sort over the last axis. Returns ------- indices : (N,) ndarray of ints Array of indices that sort the keys along the specified axis. See Also -------- argsort : Indirect sort. ndarray.sort : In-place sort. sort : Return a sorted copy of an array. Examples -------- Sort names: first by surname, then by name. >>> surnames = ('Hertz', 'Galilei', 'Hertz') >>> first_names = ('Heinrich', 'Galileo', 'Gustav') >>> ind = np.lexsort((first_names, surnames)) >>> ind array([1, 2, 0]) >>> [surnames[i] + ", " + first_names[i] for i in ind] ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich'] Sort two columns of numbers: >>> a = [1,5,1,4,3,4,4] # First column >>> b = [9,4,0,4,0,2,1] # Second column >>> ind = np.lexsort((b,a)) # Sort by a, then by b >>> ind array([2, 0, 4, 6, 5, 3, 1]) >>> [(a[i],b[i]) for i in ind] [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)] Note that sorting is first according to the elements of ``a``. Secondary sorting is according to the elements of ``b``. A normal ``argsort`` would have yielded: >>> [(a[i],b[i]) for i in np.argsort(a)] [(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)] Structured arrays are sorted lexically by ``argsort``: >>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)], ... dtype=np.dtype([('x', int), ('y', int)])) >>> np.argsort(x) # or np.argsort(x, order=('x', 'y')) array([2, 0, 4, 6, 5, 3, 1]) linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0) Return evenly spaced numbers over a specified interval. Returns `num` evenly spaced samples, calculated over the interval [`start`, `stop`]. The endpoint of the interval can optionally be excluded. .. versionchanged:: 1.16.0 Non-scalar `start` and `stop` are now supported. .. versionchanged:: 1.20.0 Values are rounded towards ``-inf`` instead of ``0`` when an integer ``dtype`` is specified. The old behavior can still be obtained with ``np.linspace(start, stop, num).astype(int)`` Parameters ---------- start : array_like The starting value of the sequence. stop : array_like The end value of the sequence, unless `endpoint` is set to False. In that case, the sequence consists of all but the last of ``num + 1`` evenly spaced samples, so that `stop` is excluded. Note that the step size changes when `endpoint` is False. num : int, optional Number of samples to generate. Default is 50. Must be non-negative. endpoint : bool, optional If True, `stop` is the last sample. Otherwise, it is not included. Default is True. retstep : bool, optional If True, return (`samples`, `step`), where `step` is the spacing between samples. dtype : dtype, optional 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. .. versionadded:: 1.9.0 axis : int, 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. .. versionadded:: 1.16.0 Returns ------- samples : ndarray There are `num` equally spaced samples in the closed interval ``[start, stop]`` or the half-open interval ``[start, stop)`` (depending on whether `endpoint` is True or False). step : float, optional Only returned if `retstep` is True Size of spacing between samples. See Also -------- arange : Similar to `linspace`, but uses a step size (instead of the number of samples). geomspace : Similar to `linspace`, but with numbers spaced evenly on a log scale (a geometric progression). logspace : Similar to `geomspace`, but with the end points specified as logarithms. Examples -------- >>> np.linspace(2.0, 3.0, num=5) array([2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25) Graphical illustration: >>> import matplotlib.pyplot as plt >>> N = 8 >>> y = np.zeros(N) >>> x1 = np.linspace(0, 10, N, endpoint=True) >>> x2 = np.linspace(0, 10, N, endpoint=False) >>> plt.plot(x1, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show() load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII') Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files. .. warning:: Loading files that contain object arrays uses the ``pickle`` module, which is not secure against erroneous or maliciously constructed data. Consider passing ``allow_pickle=False`` to load data that is known not to contain object arrays for the safer handling of untrusted sources. Parameters ---------- file : file-like object, string, or pathlib.Path The file to read. File-like objects must support the ``seek()`` and ``read()`` methods. Pickled files require that the file-like object support the ``readline()`` method as well. mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional If not None, then memory-map the file, using the given mode (see `numpy.memmap` for a detailed description of the modes). A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory. allow_pickle : bool, optional Allow loading pickled object arrays stored in npy files. Reasons for disallowing pickles include security, as loading pickled data can execute arbitrary code. If pickles are disallowed, loading object arrays will fail. Default: False .. versionchanged:: 1.16.3 Made default False in response to CVE-2019-6446. fix_imports : bool, optional Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. If `fix_imports` is True, pickle will try to map the old Python 2 names to the new names used in Python 3. encoding : str, optional What encoding to use when reading Python 2 strings. Only useful when loading Python 2 generated pickled files in Python 3, which includes npy/npz files containing object arrays. Values other than 'latin1', 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical data. Default: 'ASCII' Returns ------- result : array, tuple, dict, etc. Data stored in the file. For ``.npz`` files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors. Raises ------ IOError If the input file does not exist or cannot be read. ValueError The file contains an object array, but allow_pickle=False given. See Also -------- save, savez, savez_compressed, loadtxt memmap : Create a memory-map to an array stored in a file on disk. lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file. Notes ----- - If the file contains pickle data, then whatever object is stored in the pickle is returned. - If the file is a ``.npy`` file, then a single array is returned. - If the file is a ``.npz`` file, then a dictionary-like object is returned, containing ``{filename: array}`` key-value pairs, one for each file in the archive. - If the file is a ``.npz`` file, the returned value supports the context manager protocol in a similar fashion to the open function:: with load('foo.npz') as data: a = data['a'] The underlying file descriptor is closed when exiting the 'with' block. Examples -------- Store data to disk, and load it again: >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]])) >>> np.load('/tmp/123.npy') array([[1, 2, 3], [4, 5, 6]]) Store compressed data to disk, and load it again: >>> a=np.array([[1, 2, 3], [4, 5, 6]]) >>> b=np.array([1, 2]) >>> np.savez('/tmp/123.npz', a=a, b=b) >>> data = np.load('/tmp/123.npz') >>> data['a'] array([[1, 2, 3], [4, 5, 6]]) >>> data['b'] array([1, 2]) >>> data.close() Mem-map the stored array, and then access the second row directly from disk: >>> X = np.load('/tmp/123.npy', mmap_mode='r') >>> X[1, :] memmap([4, 5, 6]) loads(*args, **kwargs) loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, like=None) Load data from a text file. Each row in the text file must have the same number of values. Parameters ---------- fname : file, str, or pathlib.Path File, filename, or generator to read. If the filename extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note that generators should return byte strings. dtype : data-type, optional Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type. comments : str or sequence of str, optional The characters or list of characters used to indicate the start of a comment. None implies no comments. For backwards compatibility, byte strings will be decoded as 'latin1'. The default is '#'. delimiter : str, optional The string used to separate values. For backwards compatibility, byte strings will be decoded as 'latin1'. The default is whitespace. converters : dict, optional A dictionary mapping column number to a function that will parse the column string into the desired value. E.g., if column 0 is a date string: ``converters = {0: datestr2num}``. Converters can also be used to provide a default value for missing data (but see also `genfromtxt`): ``converters = {3: lambda s: float(s.strip() or 0)}``. Default: None. skiprows : int, optional Skip the first `skiprows` lines, including comments; default: 0. usecols : int or sequence, optional Which columns to read, with 0 being the first. For example, ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. .. versionchanged:: 1.11.0 When a single column has to be read it is possible to use an integer instead of a tuple. E.g ``usecols = 3`` reads the fourth column the same way as ``usecols = (3,)`` would. unpack : bool, optional If True, the returned array is transposed, so that arguments may be unpacked using ``x, y, z = loadtxt(...)``. When used with a structured data-type, arrays are returned for each field. Default is False. ndmin : int, optional The returned array will have at least `ndmin` dimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2. .. versionadded:: 1.6.0 encoding : str, optional Encoding used to decode the inputfile. Does not apply to input streams. The special value 'bytes' enables backward compatibility workarounds that ensures you receive byte arrays as results if 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'. .. versionadded:: 1.14.0 max_rows : int, optional Read `max_rows` lines of content after `skiprows` lines. The default is to read all the lines. .. versionadded:: 1.16.0 like : array_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. .. versionadded:: 1.20.0 Returns ------- out : ndarray Data read from the text file. See Also -------- load, fromstring, fromregex genfromtxt : Load data with missing values handled as specified. scipy.io.loadmat : reads MATLAB data files Notes ----- This function aims to be a fast reader for simply formatted files. The `genfromtxt` function provides more sophisticated handling of, e.g., lines with missing values. .. versionadded:: 1.10.0 The strings produced by the Python float.hex method can be used as input for floats. Examples -------- >>> from io import StringIO # StringIO behaves like a file object >>> c = StringIO("0 1\n2 3") >>> np.loadtxt(c) array([[0., 1.], [2., 3.]]) >>> d = StringIO("M 21 72\nF 35 58") >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'), ... 'formats': ('S1', 'i4', 'f4')}) array([(b'M', 21, 72.), (b'F', 35, 58.)], dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')]) >>> c = StringIO("1,0,2\n3,0,4") >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True) >>> x array([1., 3.]) >>> y array([2., 4.]) This example shows how `converters` can be used to convert a field with a trailing minus sign into a negative number. >>> s = StringIO('10.01 31.25-\n19.22 64.31\n17.57- 63.94') >>> def conv(fld): ... return -float(fld[:-1]) if fld.endswith(b'-') else float(fld) ... >>> np.loadtxt(s, converters={0: conv, 1: conv}) array([[ 10.01, -31.25], [ 19.22, 64.31], [-17.57, 63.94]]) logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0) Return numbers spaced evenly on a log scale. In linear space, the sequence starts at ``base ** start`` (`base` to the power of `start`) and ends with ``base ** stop`` (see `endpoint` below). .. versionchanged:: 1.16.0 Non-scalar `start` and `stop` are now supported. Parameters ---------- start : array_like ``base ** start`` is the starting value of the sequence. stop : array_like ``base ** stop`` is 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. num : integer, optional Number of samples to generate. Default is 50. endpoint : boolean, optional If true, `stop` is the last sample. Otherwise, it is not included. Default is True. base : array_like, optional The base of the log space. The step size between the elements in ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform. Default is 10.0. dtype : dtype The type of the output array. If `dtype` is not given, the data type is inferred from `start` and `stop`. The inferred type will never be an integer; `float` is chosen even if the arguments would produce an array of integers. axis : int, 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. .. versionadded:: 1.16.0 Returns ------- samples : ndarray `num` samples, equally spaced on a log scale. See Also -------- arange : Similar to linspace, with the step size specified instead of the number of samples. Note that, when used with a float endpoint, the endpoint may or may not be included. linspace : Similar to logspace, but with the samples uniformly distributed in linear space, instead of log space. geomspace : Similar to logspace, but with endpoints specified directly. Notes ----- Logspace is equivalent to the code >>> y = np.linspace(start, stop, num=num, endpoint=endpoint) ... # doctest: +SKIP >>> power(base, y).astype(dtype) ... # doctest: +SKIP Examples -------- >>> np.logspace(2.0, 3.0, num=4) array([ 100. , 215.443469 , 464.15888336, 1000. ]) >>> np.logspace(2.0, 3.0, num=4, endpoint=False) array([100. , 177.827941 , 316.22776602, 562.34132519]) >>> np.logspace(2.0, 3.0, num=4, base=2.0) array([4. , 5.0396842 , 6.34960421, 8. ]) Graphical illustration: >>> import matplotlib.pyplot as plt >>> N = 10 >>> x1 = np.logspace(0.1, 1, N, endpoint=True) >>> x2 = np.logspace(0.1, 1, N, endpoint=False) >>> y = np.zeros(N) >>> plt.plot(x1, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show() lookfor(what, module=None, import_modules=True, regenerate=False, output=None) Do a keyword search on docstrings. A list of objects that matched the search is displayed, sorted by relevance. All given keywords need to be found in the docstring for it to be returned as a result, but the order does not matter. Parameters ---------- what : str String containing words to look for. module : str or list, optional Name of module(s) whose docstrings to go through. import_modules : bool, optional Whether to import sub-modules in packages. Default is True. regenerate : bool, optional Whether to re-generate the docstring cache. Default is False. output : file-like, optional File-like object to write the output to. If omitted, use a pager. See Also -------- source, info Notes ----- Relevance is determined only roughly, by checking if the keywords occur in the function name, at the start of a docstring, etc. Examples -------- >>> np.lookfor('binary representation') # doctest: +SKIP Search results for 'binary representation' ------------------------------------------ numpy.binary_repr Return the binary representation of the input number as a string. numpy.core.setup_common.long_double_representation Given a binary dump as given by GNU od -b, look for long double numpy.base_repr Return a string representation of a number in the given base system. ... mafromtxt(fname, **kwargs) Load ASCII data stored in a text file and return a masked array. .. deprecated:: 1.17 np.mafromtxt is a deprecated alias of `genfromtxt` which overwrites the ``usemask`` argument with `True` even when explicitly called as ``mafromtxt(..., usemask=False)``. Use `genfromtxt` instead. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function to load ASCII data. mask_indices(n, mask_func, k=0) Return the indices to access (n, n) arrays, given a masking function. Assume `mask_func` is a function that, for a square array a of size ``(n, n)`` with a possible offset argument `k`, when called as ``mask_func(a, k)`` returns a new array with zeros in certain locations (functions like `triu` or `tril` do precisely this). Then this function returns the indices where the non-zero values would be located. Parameters ---------- n : int The returned indices will be valid to access arrays of shape (n, n). mask_func : callable A function whose call signature is similar to that of `triu`, `tril`. That is, ``mask_func(x, k)`` returns a boolean array, shaped like `x`. `k` is an optional argument to the function. k : scalar An optional argument which is passed through to `mask_func`. Functions like `triu`, `tril` take a second argument that is interpreted as an offset. Returns ------- indices : tuple of arrays. The `n` arrays of indices corresponding to the locations where ``mask_func(np.ones((n, n)), k)`` is True. See Also -------- triu, tril, triu_indices, tril_indices Notes ----- .. versionadded:: 1.4.0 Examples -------- These are the indices that would allow you to access the upper triangular part of any 3x3 array: >>> iu = np.mask_indices(3, np.triu) For example, if `a` is a 3x3 array: >>> a = np.arange(9).reshape(3, 3) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> a[iu] array([0, 1, 2, 4, 5, 8]) An offset can be passed also to the masking function. This gets us the indices starting on the first diagonal right of the main one: >>> iu1 = np.mask_indices(3, np.triu, 1) with which we now extract only three elements: >>> a[iu1] array([1, 2, 5]) mat = asmatrix(data, dtype=None) Interpret the input as a matrix. Unlike `matrix`, `asmatrix` does not make a copy if the input is already a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``. Parameters ---------- data : array_like Input data. dtype : data-type Data-type of the output matrix. Returns ------- mat : matrix `data` interpreted as a matrix. Examples -------- >>> x = np.array([[1, 2], [3, 4]]) >>> m = np.asmatrix(x) >>> x[0,0] = 5 >>> m matrix([[5, 2], [3, 4]]) maximum_sctype(t) Return the scalar type of highest precision of the same kind as the input. Parameters ---------- t : dtype or dtype specifier The input data type. This can be a `dtype` object or an object that is convertible to a `dtype`. Returns ------- out : dtype The highest precision data type of the same kind (`dtype.kind`) as `t`. See Also -------- obj2sctype, mintypecode, sctype2char dtype Examples -------- >>> np.maximum_sctype(int) <class 'numpy.int64'> >>> np.maximum_sctype(np.uint8) <class 'numpy.uint64'> >>> np.maximum_sctype(complex) <class 'numpy.complex256'> # may vary >>> np.maximum_sctype(str) <class 'numpy.str_'> >>> np.maximum_sctype('i2') <class 'numpy.int64'> >>> np.maximum_sctype('f4') <class 'numpy.float128'> # may vary may_share_memory(...) may_share_memory(a, b, max_work=None) Determine if two arrays might share memory A return of True does not necessarily mean that the two arrays share any element. It just means that they *might*. Only the memory bounds of a and b are checked by default. Parameters ---------- a, b : ndarray Input arrays max_work : int, optional Effort to spend on solving the overlap problem. See `shares_memory` for details. Default for ``may_share_memory`` is to do a bounds check. Returns ------- out : bool See Also -------- shares_memory Examples -------- >>> np.may_share_memory(np.array([1,2]), np.array([5,8,9])) False >>> x = np.zeros([3, 4]) >>> np.may_share_memory(x[:,0], x[:,1]) True mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>) Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. `float64` intermediate and return values are used for integer inputs. Parameters ---------- a : array_like Array containing numbers whose mean is desired. If `a` is not an array, a conversion is attempted. axis : None or int or tuple of ints, optional Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. .. versionadded:: 1.7.0 If this is a tuple of ints, a mean is performed over multiple axes, instead of a single axis or all the axes as before. dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for floating point inputs, it is the same as the input dtype. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See :ref:`ufuncs-output-type` for more details. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then `keepdims` will not be passed through to the `mean` method of sub-classes of `ndarray`, however any non-default value will be. If the sub-class' method does not implement `keepdims` any exceptions will be raised. where : array_like of bool, optional Elements to include in the mean. See `~numpy.ufunc.reduce` for details. .. versionadded:: 1.20.0 Returns ------- m : ndarray, see dtype parameter above If `out=None`, returns a new array containing the mean values, otherwise a reference to the output array is returned. See Also -------- average : Weighted average std, var, nanmean, nanstd, nanvar Notes ----- The arithmetic mean is the sum of the elements along the axis divided by the number of elements. Note that for floating-point input, the mean is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for `float32` (see example below). Specifying a higher-precision accumulator using the `dtype` keyword can alleviate this issue. By default, `float16` results are computed using `float32` intermediates for extra precision. Examples -------- >>> a = np.array([[1, 2], [3, 4]]) >>> np.mean(a) 2.5 >>> np.mean(a, axis=0) array([2., 3.]) >>> np.mean(a, axis=1) array([1.5, 3.5]) In single precision, `mean` can be inaccurate: >>> a = np.zeros((2, 512*512), dtype=np.float32) >>> a[0, :] = 1.0 >>> a[1, :] = 0.1 >>> np.mean(a) 0.54999924 Computing the mean in float64 is more accurate: >>> np.mean(a, dtype=np.float64) 0.55000000074505806 # may vary Specifying a where argument: >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]]) >>> np.mean(a) 12.0 >>> np.mean(a, where=[[True], [False], [False]]) 9.0 median(a, axis=None, out=None, overwrite_input=False, keepdims=False) Compute the median along the specified axis. Returns the median of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : {int, sequence of int, None}, optional Axis or axes along which the medians are computed. The default is to compute the median along a flattened version of the array. A sequence of axes is supported since version 1.9.0. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow use of memory of input array `a` for calculations. The input array will be modified by the call to `median`. This will save memory when you do not need to preserve the contents of the input array. Treat the input as undefined, but it will probably be fully or partially sorted. Default is False. If `overwrite_input` is ``True`` and `a` is not already an `ndarray`, an error will be raised. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. .. versionadded:: 1.9.0 Returns ------- median : ndarray A new array holding the result. If the input contains integers or floats smaller than ``float64``, then the output data-type is ``np.float64``. Otherwise, the data-type of the output is the same as that of the input. If `out` is specified, that array is returned instead. See Also -------- mean, percentile Notes ----- Given a vector ``V`` of length ``N``, the median of ``V`` is the middle value of a sorted copy of ``V``, ``V_sorted`` - i e., ``V_sorted[(N-1)/2]``, when ``N`` is odd, and the average of the two middle values of ``V_sorted`` when ``N`` is even. Examples -------- >>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> a array([[10, 7, 4], [ 3, 2, 1]]) >>> np.median(a) 3.5 >>> np.median(a, axis=0) array([6.5, 4.5, 2.5]) >>> np.median(a, axis=1) array([7., 2.]) >>> m = np.median(a, axis=0) >>> out = np.zeros_like(m) >>> np.median(a, axis=0, out=m) array([6.5, 4.5, 2.5]) >>> m array([6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.median(b, axis=1, overwrite_input=True) array([7., 2.]) >>> assert not np.all(a==b) >>> b = a.copy() >>> np.median(b, axis=None, overwrite_input=True) 3.5 >>> assert not np.all(a==b) meshgrid(*xi, copy=True, sparse=False, indexing='xy') Return coordinate matrices from coordinate vectors. Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn. .. versionchanged:: 1.9 1-D and 0-D cases are allowed. Parameters ---------- x1, x2,..., xn : array_like 1-D arrays representing the coordinates of a grid. indexing : {'xy', 'ij'}, optional Cartesian ('xy', default) or matrix ('ij') indexing of output. See Notes for more details. .. versionadded:: 1.7.0 sparse : bool, optional If True a sparse grid is returned in order to conserve memory. Default is False. .. versionadded:: 1.7.0 copy : bool, optional If False, a view into the original arrays are returned in order to conserve memory. Default is True. Please note that ``sparse=False, copy=False`` will likely return non-contiguous arrays. Furthermore, more than one element of a broadcast array may refer to a single memory location. If you need to write to the arrays, make copies first. .. versionadded:: 1.7.0 Returns ------- X1, X2,..., XN : ndarray For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` , return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij' or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy' with the elements of `xi` repeated to fill the matrix along the first dimension for `x1`, the second for `x2` and so on. Notes ----- This function supports both indexing conventions through the indexing keyword argument. Giving the string 'ij' returns a meshgrid with matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing. In the 2-D case with inputs of length M and N, the outputs are of shape (N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case with inputs of length M, N and P, outputs are of shape (N, M, P) for 'xy' indexing and (M, N, P) for 'ij' indexing. The difference is illustrated by the following code snippet:: xv, yv = np.meshgrid(x, y, sparse=False, indexing='ij') for i in range(nx): for j in range(ny): # treat xv[i,j], yv[i,j] xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy') for i in range(nx): for j in range(ny): # treat xv[j,i], yv[j,i] In the 1-D and 0-D case, the indexing and sparse keywords have no effect. See Also -------- mgrid : Construct a multi-dimensional "meshgrid" using indexing notation. ogrid : Construct an open multi-dimensional "meshgrid" using indexing notation. Examples -------- >>> nx, ny = (3, 2) >>> x = np.linspace(0, 1, nx) >>> y = np.linspace(0, 1, ny) >>> xv, yv = np.meshgrid(x, y) >>> xv array([[0. , 0.5, 1. ], [0. , 0.5, 1. ]]) >>> yv array([[0., 0., 0.], [1., 1., 1.]]) >>> xv, yv = np.meshgrid(x, y, sparse=True) # make sparse output arrays >>> xv array([[0. , 0.5, 1. ]]) >>> yv array([[0.], [1.]]) `meshgrid` is very useful to evaluate functions on a grid. >>> import matplotlib.pyplot as plt >>> x = np.arange(-5, 5, 0.1) >>> y = np.arange(-5, 5, 0.1) >>> xx, yy = np.meshgrid(x, y, sparse=True) >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) >>> h = plt.contourf(x, y, z) >>> plt.axis('scaled') >>> plt.show() min_scalar_type(...) min_scalar_type(a) For scalar ``a``, returns the data type with the smallest size and smallest scalar kind which can hold its value. For non-scalar array ``a``, returns the vector's dtype unmodified. Floating point values are not demoted to integers, and complex values are not demoted to floats. Parameters ---------- a : scalar or array_like The value whose minimal data type is to be found. Returns ------- out : dtype The minimal data type. Notes ----- .. versionadded:: 1.6.0 See Also -------- result_type, promote_types, dtype, can_cast Examples -------- >>> np.min_scalar_type(10) dtype('uint8') >>> np.min_scalar_type(-260) dtype('int16') >>> np.min_scalar_type(3.1) dtype('float16') >>> np.min_scalar_type(1e50) dtype('float64') >>> np.min_scalar_type(np.arange(4,dtype='f8')) dtype('float64') mintypecode(typechars, typeset='GDFgdf', default='d') Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in `typechars` (or if `typechars` is an array, then its dtype.char). Parameters ---------- typechars : list of str or array_like If a list of strings, each string should represent a dtype. If array_like, the character representation of the array dtype is used. typeset : str or list of str, optional The set of characters that the returned character is chosen from. The default set is 'GDFgdf'. default : str, optional The default character, this is returned if none of the characters in `typechars` matches a character in `typeset`. Returns ------- typechar : str The character representing the minimum-size type that was found. See Also -------- dtype, sctype2char, maximum_sctype Examples -------- >>> np.mintypecode(['d', 'f', 'S']) 'd' >>> x = np.array([1.1, 2-3.j]) >>> np.mintypecode(x) 'D' >>> np.mintypecode('abceh', default='G') 'G' moveaxis(a, source, destination) Move axes of an array to new positions. Other axes remain in their original order. .. versionadded:: 1.11.0 Parameters ---------- a : np.ndarray The array whose axes should be reordered. source : int or sequence of int Original positions of the axes to move. These must be unique. destination : int or sequence of int Destination positions for each of the original axes. These must also be unique. Returns ------- result : np.ndarray Array with moved axes. This array is a view of the input array. See Also -------- transpose : Permute the dimensions of an array. swapaxes : Interchange two axes of an array. Examples -------- >>> x = np.zeros((3, 4, 5)) >>> np.moveaxis(x, 0, -1).shape (4, 5, 3) >>> np.moveaxis(x, -1, 0).shape (5, 3, 4) These all achieve the same result: >>> np.transpose(x).shape (5, 4, 3) >>> np.swapaxes(x, 0, -1).shape (5, 4, 3) >>> np.moveaxis(x, [0, 1], [-1, -2]).shape (5, 4, 3) >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape (5, 4, 3) msort(a) Return a copy of an array sorted along the first axis. Parameters ---------- a : array_like Array to be sorted. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- sort Notes ----- ``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``. nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None) Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the numbers defined by the user using the `nan`, `posinf` and/or `neginf` keywords. If `x` is inexact, NaN is replaced by zero or by the user defined value in `nan` keyword, infinity is replaced by the largest finite floating point values representable by ``x.dtype`` or by the user defined value in `posinf` keyword and -infinity is replaced by the most negative finite floating point values representable by ``x.dtype`` or by the user defined value in `neginf` keyword. For complex dtypes, the above is applied to each of the real and imaginary components of `x` separately. If `x` is not inexact, then no replacements are made. Parameters ---------- x : scalar or array_like Input data. copy : bool, optional Whether to create a copy of `x` (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True. .. versionadded:: 1.13 nan : int, float, optional Value to be used to fill NaN values. If no value is passed then NaN values will be replaced with 0.0. .. versionadded:: 1.17 posinf : int, float, optional Value to be used to fill positive infinity values. If no value is passed then positive infinity values will be replaced with a very large number. .. versionadded:: 1.17 neginf : int, float, optional Value to be used to fill negative infinity values. If no value is passed then negative infinity values will be replaced with a very small (or negative) number. .. versionadded:: 1.17 Returns ------- out : ndarray `x`, with the non-finite values replaced. If `copy` is False, this may be `x` itself. See Also -------- isinf : Shows which elements are positive or negative infinity. isneginf : Shows which elements are negative infinity. isposinf : Shows which elements are positive infinity. isnan : Shows which elements are Not a Number (NaN). isfinite : Shows which elements are finite (not NaN, not infinity) Notes ----- NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Examples -------- >>> np.nan_to_num(np.inf) 1.7976931348623157e+308 >>> np.nan_to_num(-np.inf) -1.7976931348623157e+308 >>> np.nan_to_num(np.nan) 0.0 >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333) array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03, -1.2800000e+02, 1.2800000e+02]) >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)]) array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary -1.28000000e+002, 1.28000000e+002]) >>> np.nan_to_num(y) array([ 1.79769313e+308 +0.00000000e+000j, # may vary 0.00000000e+000 +0.00000000e+000j, 0.00000000e+000 +1.79769313e+308j]) >>> np.nan_to_num(y, nan=111111, posinf=222222) array([222222.+111111.j, 111111. +0.j, 111111.+222222.j]) nanargmax(a, axis=None) Return the indices of the maximum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmax, nanargmin Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmax(a) 0 >>> np.nanargmax(a) 1 >>> np.nanargmax(a, axis=0) array([1, 0]) >>> np.nanargmax(a, axis=1) array([1, 1]) nanargmin(a, axis=None) Return the indices of the minimum values in the specified axis ignoring NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs. Parameters ---------- a : array_like Input data. axis : int, optional Axis along which to operate. By default flattened input is used. Returns ------- index_array : ndarray An array of indices or a single index value. See Also -------- argmin, nanargmax Examples -------- >>> a = np.array([[np.nan, 4], [2, 3]]) >>> np.argmin(a) 0 >>> np.nanargmin(a) 2 >>> np.nanargmin(a, axis=0) array([1, 1]) >>> np.nanargmin(a, axis=1) array([1, 0]) nancumprod(a, axis=None, dtype=None, out=None) Return the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) as one. The cumulative product does not change when NaNs are encountered and leading NaNs are replaced by ones. Ones are returned for slices that are all-NaN or empty. .. versionadded:: 1.12.0 Parameters ---------- a : array_like Input array. axis : int, optional Axis along which the cumulative product is computed. By default the input is flattened. dtype : dtype, optional Type of the returned array, as well as of the accumulator in which the elements are multiplied. If *dtype* is not specified, it defaults to the dtype of `a`, unless `a` has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used instead. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type of the resulting values will be cast if necessary. Returns ------- nancumprod : ndarray A new array holding the result is returned unless `out` is specified, in which case it is returned. See Also -------- numpy.cumprod : Cumulative product across array propagating NaNs. isnan : Show which elements are NaN. Examples -------- >>> np.nancumprod(1) array([1]) >>> np.nancumprod([1]) array([1]) >>> np.nancumprod([1, np.nan]) array([1., 1.]) >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nancumprod(a) array([1., 2., 6., 6.]) >>> np.nancumprod(a, axis=0) array([[1., 2.], [3., 2.]]) >>> np.nancumprod(a, axis=1) array([[1., 2.], [3., 3.]]) nancumsum(a, axis=None, dtype=None, out=None) Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros. Zeros are returned for slices that are all-NaN or empty. .. versionadded:: 1.12.0 Parameters ---------- a : array_like Input array. axis : int, optional Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. dtype : dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults to the dtype of `a`, unless `a` has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. See :ref:`ufuncs-output-type` for more details. Returns ------- nancumsum : ndarray. A new array holding the result is returned unless `out` is specified, in which it is returned. The result has the same size as `a`, and the same shape as `a` if `axis` is not None or `a` is a 1-d array. See Also -------- numpy.cumsum : Cumulative sum across array propagating NaNs. isnan : Show which elements are NaN. Examples -------- >>> np.nancumsum(1) array([1]) >>> np.nancumsum([1]) array([1]) >>> np.nancumsum([1, np.nan]) array([1., 1.]) >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nancumsum(a) array([1., 3., 6., 6.]) >>> np.nancumsum(a, axis=0) array([[1., 2.], [4., 2.]]) >>> np.nancumsum(a, axis=1) array([[1., 3.], [3., 3.]]) nanmax(a, axis=None, out=None, keepdims=<no value>) Return the maximum of an array or maximum along an axis, ignoring any NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is raised and NaN is returned for that slice. Parameters ---------- a : array_like Array containing numbers whose maximum is desired. If `a` is not an array, a conversion is attempted. axis : {int, tuple of int, None}, optional Axis or axes along which the maximum is computed. The default is to compute the maximum of the flattened array. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See :ref:`ufuncs-output-type` for more details. .. versionadded:: 1.8.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If the value is anything but the default, then `keepdims` will be passed through to the `max` method of sub-classes of `ndarray`. If the sub-classes methods does not implement `keepdims` any exceptions will be raised. .. versionadded:: 1.8.0 Returns ------- nanmax : ndarray An array with the same shape as `a`, with the specified axis removed. If `a` is a 0-d array, or if axis is None, an ndarray scalar is returned. The same dtype as `a` is returned. See Also -------- nanmin : The minimum value of an array along a given axis, ignoring any NaNs. amax : The maximum value of an array along a given axis, propagating any NaNs. fmax : Element-wise maximum of two arrays, ignoring any NaNs. maximum : Element-wise maximum of two arrays, propagating any NaNs. isnan : Shows which elements are Not a Number (NaN). isfinite: Shows which elements are neither NaN nor infinity. amin, fmin, minimum Notes ----- NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is treated as a very small (i.e. negative) number. If the input has a integer type the function is equivalent to np.max. Examples -------- >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanmax(a) 3.0 >>> np.nanmax(a, axis=0) array([3., 2.]) >>> np.nanmax(a, axis=1) array([2., 3.]) When positive infinity and negative infinity are present: >>> np.nanmax([1, 2, np.nan, np.NINF]) 2.0 >>> np.nanmax([1, 2, np.nan, np.inf]) inf nanmean(a, axis=None, dtype=None, out=None, keepdims=<no value>) Compute the arithmetic mean along the specified axis, ignoring NaNs. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. `float64` intermediate and return values are used for integer inputs. For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Array containing numbers whose mean is desired. If `a` is not an array, a conversion is attempted. axis : {int, tuple of int, None}, optional Axis or axes along which the means are computed. The default is to compute the mean of the flattened array. dtype : data-type, optional Type to use in computing the mean. For integer inputs, the default is `float64`; for inexact inputs, it is the same as the input dtype. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See :ref:`ufuncs-output-type` for more details. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If the value is anything but the default, then `keepdims` will be passed through to the `mean` or `sum` methods of sub-classes of `ndarray`. If the sub-classes methods does not implement `keepdims` any exceptions will be raised. Returns ------- m : ndarray, see dtype parameter above If `out=None`, returns a new array containing the mean values, otherwise a reference to the output array is returned. Nan is returned for slices that contain only NaNs. See Also -------- average : Weighted average mean : Arithmetic mean taken while not ignoring NaNs var, nanvar Notes ----- The arithmetic mean is the sum of the non-NaN elements along the axis divided by the number of non-NaN elements. Note that for floating-point input, the mean is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for `float32`. Specifying a higher-precision accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, np.nan], [3, 4]]) >>> np.nanmean(a) 2.6666666666666665 >>> np.nanmean(a, axis=0) array([2., 4.]) >>> np.nanmean(a, axis=1) array([1., 3.5]) # may vary nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=<no value>) Compute the median along the specified axis, while ignoring NaNs. Returns the median of the array elements. .. versionadded:: 1.9.0 Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : {int, sequence of int, None}, optional Axis or axes along which the medians are computed. The default is to compute the median along a flattened version of the array. A sequence of axes is supported since version 1.9.0. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow use of memory of input array `a` for calculations. The input array will be modified by the call to `median`. This will save memory when you do not need to preserve the contents of the input array. Treat the input as undefined, but it will probably be fully or partially sorted. Default is False. If `overwrite_input` is ``True`` and `a` is not already an `ndarray`, an error will be raised. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If this is anything but the default value it will be passed through (in the special case of an empty array) to the `mean` function of the underlying array. If the array is a sub-class and `mean` does not have the kwarg `keepdims` this will raise a RuntimeError. Returns ------- median : ndarray A new array holding the result. If the input contains integers or floats smaller than ``float64``, then the output data-type is ``np.float64``. Otherwise, the data-type of the output is the same as that of the input. If `out` is specified, that array is returned instead. See Also -------- mean, median, percentile Notes ----- Given a vector ``V`` of length ``N``, the median of ``V`` is the middle value of a sorted copy of ``V``, ``V_sorted`` - i.e., ``V_sorted[(N-1)/2]``, when ``N`` is odd and the average of the two middle values of ``V_sorted`` when ``N`` is even. Examples -------- >>> a = np.array([[10.0, 7, 4], [3, 2, 1]]) >>> a[0, 1] = np.nan >>> a array([[10., nan, 4.], [ 3., 2., 1.]]) >>> np.median(a) nan >>> np.nanmedian(a) 3.0 >>> np.nanmedian(a, axis=0) array([6.5, 2. , 2.5]) >>> np.median(a, axis=1) array([nan, 2.]) >>> b = a.copy() >>> np.nanmedian(b, axis=1, overwrite_input=True) array([7., 2.]) >>> assert not np.all(a==b) >>> b = a.copy() >>> np.nanmedian(b, axis=None, overwrite_input=True) 3.0 >>> assert not np.all(a==b) nanmin(a, axis=None, out=None, keepdims=<no value>) Return minimum of an array or minimum along an axis, ignoring any NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is raised and Nan is returned for that slice. Parameters ---------- a : array_like Array containing numbers whose minimum is desired. If `a` is not an array, a conversion is attempted. axis : {int, tuple of int, None}, optional Axis or axes along which the minimum is computed. The default is to compute the minimum of the flattened array. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``; if provided, it must have the same shape as the expected output, but the type will be cast if necessary. See :ref:`ufuncs-output-type` for more details. .. versionadded:: 1.8.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If the value is anything but the default, then `keepdims` will be passed through to the `min` method of sub-classes of `ndarray`. If the sub-classes methods does not implement `keepdims` any exceptions will be raised. .. versionadded:: 1.8.0 Returns ------- nanmin : ndarray An array with the same shape as `a`, with the specified axis removed. If `a` is a 0-d array, or if axis is None, an ndarray scalar is returned. The same dtype as `a` is returned. See Also -------- nanmax : The maximum value of an array along a given axis, ignoring any NaNs. amin : The minimum value of an array along a given axis, propagating any NaNs. fmin : Element-wise minimum of two arrays, ignoring any NaNs. minimum : Element-wise minimum of two arrays, propagating any NaNs. isnan : Shows which elements are Not a Number (NaN). isfinite: Shows which elements are neither NaN nor infinity. amax, fmax, maximum Notes ----- NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is treated as a very small (i.e. negative) number. If the input has a integer type the function is equivalent to np.min. Examples -------- >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanmin(a) 1.0 >>> np.nanmin(a, axis=0) array([1., 2.]) >>> np.nanmin(a, axis=1) array([1., 3.]) When positive infinity and negative infinity are present: >>> np.nanmin([1, 2, np.nan, np.inf]) 1.0 >>> np.nanmin([1, 2, np.nan, np.NINF]) -inf nanpercentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=<no value>) Compute the qth percentile of the data along the specified axis, while ignoring nan values. Returns the qth percentile(s) of the array elements. .. versionadded:: 1.9.0 Parameters ---------- a : array_like Input array or object that can be converted to an array, containing nan values to be ignored. q : array_like of float Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive. axis : {int, tuple of int, None}, optional Axis or axes along which the percentiles are computed. The default is to compute the percentile(s) along a flattened version of the array. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow the input array `a` to be modified by intermediate calculations, to save memory. In this case, the contents of the input `a` after this function completes is undefined. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to use when the desired percentile lies between two data points ``i < j``: * 'linear': ``i + (j - i) * fraction``, where ``fraction`` is the fractional part of the index surrounded by ``i`` and ``j``. * 'lower': ``i``. * 'higher': ``j``. * 'nearest': ``i`` or ``j``, whichever is nearest. * 'midpoint': ``(i + j) / 2``. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array `a`. If this is anything but the default value it will be passed through (in the special case of an empty array) to the `mean` function of the underlying array. If the array is a sub-class and `mean` does not have the kwarg `keepdims` this will raise a RuntimeError. Returns ------- percentile : scalar or ndarray If `q` is a single percentile and `axis=None`, then the result is a scalar. If multiple percentiles are given, first axis of the result corresponds to the percentiles. The other axes are the axes that remain after the reduction of `a`. If the input contains integers or floats smaller than ``float64``, the output data-type is ``float64``. Otherwise, the output data-type is the same as that of the input. If `out` is specified, that array is returned instead. See Also -------- nanmean nanmedian : equivalent to ``nanpercentile(..., 50)`` percentile, median, mean nanquantile : equivalent to nanpercentile, but with q in the range [0, 1]. Notes ----- Given a vector ``V`` of length ``N``, the ``q``-th percentile of ``V`` is the value ``q/100`` of the way from the minimum to the maximum in a sorted copy of ``V``. The values and distances of the two nearest neighbors as well as the `interpolation` parameter will determine the percentile if the normalized ranking does not match the location of ``q`` exactly. This function is the same as the median if ``q=50``, the same as the minimum if ``q=0`` and the same as the maximum if ``q=100``. Examples -------- >>> a = np.array([[10., 7., 4.], [3., 2., 1.]]) >>> a[0][1] = np.nan >>> a array([[10., nan, 4.], [ 3., 2., 1.]]) >>> np.percentile(a, 50) nan >>> np.nanpercentile(a, 50) 3.0 >>> np.nanpercentile(a, 50, axis=0) array([6.5, 2. , 2.5]) >>> np.nanpercentile(a, 50, axis=1, keepdims=True) array([[7.], [2.]]) >>> m = np.nanpercentile(a, 50, axis=0) >>> out = np.zeros_like(m) >>> np.nanpercentile(a, 50, axis=0, out=out) array([6.5, 2. , 2.5]) >>> m array([6.5, 2. , 2.5]) >>> b = a.copy() >>> np.nanpercentile(b, 50, axis=1, overwrite_input=True) array([7., 2.]) >>> assert not np.all(a==b) nanprod(a, axis=None, dtype=None, out=None, keepdims=<no value>) Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones. One is returned for slices that are all-NaN or empty. .. versionadded:: 1.10.0 Parameters ---------- a : array_like Array containing numbers whose product is desired. If `a` is not an array, a conversion is attempted. axis : {int, tuple of int, None}, optional Axis or axes along which the product is computed. The default is to compute the product of the flattened array. dtype : data-type, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of `a` is used. An exception is when `a` has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact. out : ndarray, optional Alternate output array in which to place the result. The default is ``None``. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See :ref:`ufuncs-output-type` for more details. The casting of NaN to integer can yield unexpected results. keepdims : bool, optional If True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `arr`. Returns ------- nanprod : ndarray A new array holding the result is returned unless `out` is specified, in which case it is returned. See Also -------- numpy.prod : Product across array propagating NaNs. isnan : Show which elements are NaN. Examples -------- >>> np.nanprod(1) 1 >>> np.nanprod([1]) 1 >>> np.nanprod([1, np.nan]) 1.0 >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanprod(a) 6.0 >>> np.nanprod(a, axis=0) array([3., 2.]) nanquantile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=<no value>) Compute the qth quantile of the data along the specified axis, while ignoring nan values. Returns the qth quantile(s) of the array elements. .. versionadded:: 1.15.0 Parameters ---------- a : array_like Input array or object that can be converted to an array, containing nan values to be ignored q : array_like of float Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive. axis : {int, tuple of int, None}, optional Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output, but the type (of the output) will be cast if necessary. overwrite_input : bool, optional If True, then allow the input array `a` to be modified by intermediate calculations, to save memory. In this case, the contents of the input `a` after this function completes is undefined. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points ``i < j``: * linear: ``i + (j - i) * fraction``, where ``fraction`` is the fractional part of the index surrounded by ``i`` and ``j``. * lower: ``i``. * higher: ``j``. * nearest: ``i`` or ``j``, whichever is nearest. * midpoint: ``(i + j) / 2``. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array `a`. If this is anything but the default value it will be passed through (in the special case of an empty array) to the `mean` function of the underlying array. If the array is a sub-class and `mean` does not have the kwarg `keepdims` this will raise a RuntimeError. Returns ------- quantile : scalar or ndarray If `q` is a single percentile and `axis=None`, then the result is a scalar. If multiple quantiles are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of `a`. If the input contains integers or floats smaller than ``float64``, the output data-type is ``float64``. Otherwise, the output data-type is the same as that of the input. If `out` is specified, that array is returned instead. See Also -------- quantile nanmean, nanmedian nanmedian : equivalent to ``nanquantile(..., 0.5)`` nanpercentile : same as nanquantile, but with q in the range [0, 100]. Examples -------- >>> a = np.array([[10., 7., 4.], [3., 2., 1.]]) >>> a[0][1] = np.nan >>> a array([[10., nan, 4.], [ 3., 2., 1.]]) >>> np.quantile(a, 0.5) nan >>> np.nanquantile(a, 0.5) 3.0 >>> np.nanquantile(a, 0.5, axis=0) array([6.5, 2. , 2.5]) >>> np.nanquantile(a, 0.5, axis=1, keepdims=True) array([[7.], [2.]]) >>> m = np.nanquantile(a, 0.5, axis=0) >>> out = np.zeros_like(m) >>> np.nanquantile(a, 0.5, axis=0, out=out) array([6.5, 2. , 2.5]) >>> m array([6.5, 2. , 2.5]) >>> b = a.copy() >>> np.nanquantile(b, 0.5, axis=1, overwrite_input=True) array([7., 2.]) >>> assert not np.all(a==b) nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>) Compute the standard deviation along the specified axis, while ignoring NaNs. Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Calculate the standard deviation of the non-NaN values. axis : {int, tuple of int, None}, optional Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. dtype : dtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary. ddof : int, optional Means Delta Degrees of Freedom. The divisor used in calculations is ``N - ddof``, where ``N`` represents the number of non-NaN elements. By default `ddof` is zero. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If this value is anything but the default it is passed through as-is to the relevant functions of the sub-classes. If these functions do not have a `keepdims` kwarg, a RuntimeError will be raised. Returns ------- standard_deviation : ndarray, see dtype parameter above. If `out` is None, return a new array containing the standard deviation, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN. See Also -------- var, mean, std nanvar, nanmean :ref:`ufuncs-output-type` Notes ----- The standard deviation is the square root of the average of the squared deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``. The average squared deviation is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of the infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ``ddof=1``, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, `std` takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the *std* is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the `dtype` keyword can alleviate this issue. Examples -------- >>> a = np.array([[1, np.nan], [3, 4]]) >>> np.nanstd(a) 1.247219128924647 >>> np.nanstd(a, axis=0) array([1., 0.]) >>> np.nanstd(a, axis=1) array([0., 0.5]) # may vary nansum(a, axis=None, dtype=None, out=None, keepdims=<no value>) Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. In NumPy versions <= 1.9.0 Nan is returned for slices that are all-NaN or empty. In later versions zero is returned. Parameters ---------- a : array_like Array containing numbers whose sum is desired. If `a` is not an array, a conversion is attempted. axis : {int, tuple of int, None}, optional Axis or axes along which the sum is computed. The default is to compute the sum of the flattened array. dtype : data-type, optional The type of the returned array and of the accumulator in which the elements are summed. By default, the dtype of `a` is used. An exception is when `a` has an integer type with less precision than the platform (u)intp. In that case, the default will be either (u)int32 or (u)int64 depending on whether the platform is 32 or 64 bits. For inexact inputs, dtype must be inexact. .. versionadded:: 1.8.0 out : ndarray, optional Alternate output array in which to place the result. The default is ``None``. If provided, it must have the same shape as the expected output, but the type will be cast if necessary. See :ref:`ufuncs-output-type` for more details. The casting of NaN to integer can yield unexpected results. .. versionadded:: 1.8.0 keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. If the value is anything but the default, then `keepdims` will be passed through to the `mean` or `sum` methods of sub-classes of `ndarray`. If the sub-classes methods does not implement `keepdims` any exceptions will be raised. .. versionadded:: 1.8.0 Returns ------- nansum : ndarray. A new array holding the result is returned unless `out` is specified, in which it is returned. The result has the same size as `a`, and the same shape as `a` if `axis` is not None or `a` is a 1-d array. See Also -------- numpy.sum : Sum across array propagating NaNs. isnan : Show which elements are NaN. isfinite : Show which elements are not NaN or +/-inf. Notes ----- If both positive and negative infinity are present, the sum will be Not A Number (NaN). Examples -------- >>> np.nansum(1) 1 >>> np.nansum([1]) 1 >>> np.nansum([1, np.nan]) 1.0 >>> a = np.array([[1, 1], [1, np.nan]]) >>> np.nansum(a) 3.0 >>> np.nansum(a, axis=0) array([2., 1.]) >>> np.nansum([1, np.nan, np.inf]) inf >>> np.nansum([1, np.nan, np.NINF]) -inf >>> from numpy.testing import suppress_warnings >>> with suppress_warnings() as sup: ... sup.filter(RuntimeWarning) ... np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present nan nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>) Compute the variance along the specified axis, while ignoring NaNs. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis. For all-NaN slices or slices with zero degrees of freedom, NaN is returned and a `RuntimeWarning` is raised. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Array containing numbers whose variance is desired. If `a` is not an array, a conversion is attempted. axis : {int, tuple of int, None}, optional Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array. dtype : data-type, optional Type to use in computing the variance. For arrays of integer type the default is `float64`; for arrays of float types it is the same as the array type. out : ndarray, optional Alternate output array in which to place the result. It must have the same shape as the expected output, but the type is cast if necessary. ddof : int, optional "Delta Degrees of Freedom": the divisor used in the calculation is ``N - ddof``, where ``N`` represents the number of non-NaN elements. By default `ddof` is zero. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. Returns ------- variance : ndarray, see dtype parameter above If `out` is None, return a new array containing the variance, otherwise return a reference to the output array. If ddof is >= the number of non-NaN elements in a slice or the slice contains only NaNs, then the result for that slice is NaN. See Also -------- std : Standard deviation mean : Average var : Variance while not ignoring NaNs nanstd, nanmean :ref:`ufuncs-output-type` Notes ----- The variance is the average of the squared deviations from the mean, i.e., ``var = mean(abs(x - x.mean())**2)``. The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1`` provides an unbiased estimator of the variance of a hypothetical infinite population. ``ddof=0`` provides a maximum likelihood estimate of the variance for normally distributed variables. Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative. For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for `float32` (see example below). Specifying a higher-accuracy accumulator using the ``dtype`` keyword can alleviate this issue. For this function to work on sub-classes of ndarray, they must define `sum` with the kwarg `keepdims` Examples -------- >>> a = np.array([[1, np.nan], [3, 4]]) >>> np.nanvar(a) 1.5555555555555554 >>> np.nanvar(a, axis=0) array([1., 0.]) >>> np.nanvar(a, axis=1) array([0., 0.25]) # may vary ndfromtxt(fname, **kwargs) Load ASCII data stored in a file and return it as a single array. .. deprecated:: 1.17 ndfromtxt` is a deprecated alias of `genfromtxt` which overwrites the ``usemask`` argument with `False` even when explicitly called as ``ndfromtxt(..., usemask=True)``. Use `genfromtxt` instead. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function. ndim(a) Return the number of dimensions of an array. Parameters ---------- a : array_like Input array. If it is not already an ndarray, a conversion is attempted. Returns ------- number_of_dimensions : int The number of dimensions in `a`. Scalars are zero-dimensional. See Also -------- ndarray.ndim : equivalent method shape : dimensions of array ndarray.shape : dimensions of array Examples -------- >>> np.ndim([[1,2,3],[4,5,6]]) 2 >>> np.ndim(np.array([[1,2,3],[4,5,6]])) 2 >>> np.ndim(1) 0 nested_iters(...) Create nditers for use in nested loops Create a tuple of `nditer` objects which iterate in nested loops over different axes of the op argument. The first iterator is used in the outermost loop, the last in the innermost loop. Advancing one will change the subsequent iterators to point at its new element. Parameters ---------- op : ndarray or sequence of array_like The array(s) to iterate over. axes : list of list of int Each item is used as an "op_axes" argument to an nditer flags, op_flags, op_dtypes, order, casting, buffersize (optional) See `nditer` parameters of the same name Returns ------- iters : tuple of nditer An nditer for each item in `axes`, outermost first See Also -------- nditer Examples -------- Basic usage. Note how y is the "flattened" version of [a[:, 0, :], a[:, 1, 0], a[:, 2, :]] since we specified the first iter's axes as [1] >>> a = np.arange(12).reshape(2, 3, 2) >>> i, j = np.nested_iters(a, [[1], [0, 2]], flags=["multi_index"]) >>> for x in i: ... print(i.multi_index) ... for y in j: ... print('', j.multi_index, y) (0,) (0, 0) 0 (0, 1) 1 (1, 0) 6 (1, 1) 7 (1,) (0, 0) 2 (0, 1) 3 (1, 0) 8 (1, 1) 9 (2,) (0, 0) 4 (0, 1) 5 (1, 0) 10 (1, 1) 11 nonzero(a) Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of `a`, containing the indices of the non-zero elements in that dimension. The values in `a` are always tested and returned in row-major, C-style order. To group the indices by element, rather than dimension, use `argwhere`, which returns a row for each non-zero element. .. note:: When called on a zero-d array or scalar, ``nonzero(a)`` is treated as ``nonzero(atleast_1d(a))``. .. deprecated:: 1.17.0 Use `atleast_1d` explicitly if this behavior is deliberate. Parameters ---------- a : array_like Input array. Returns ------- tuple_of_arrays : tuple Indices of elements that are non-zero. See Also -------- flatnonzero : Return indices that are non-zero in the flattened version of the input array. ndarray.nonzero : Equivalent ndarray method. count_nonzero : Counts the number of non-zero elements in the input array. Notes ----- While the nonzero values can be obtained with ``a[nonzero(a)]``, it is recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which will correctly handle 0-d arrays. Examples -------- >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]]) >>> x array([[3, 0, 0], [0, 4, 0], [5, 6, 0]]) >>> np.nonzero(x) (array([0, 1, 2, 2]), array([0, 1, 0, 1])) >>> x[np.nonzero(x)] array([3, 4, 5, 6]) >>> np.transpose(np.nonzero(x)) array([[0, 0], [1, 1], [2, 0], [2, 1]]) A common use for ``nonzero`` is to find the indices of an array, where a condition is True. Given an array `a`, the condition `a` > 3 is a boolean array and since False is interpreted as 0, np.nonzero(a > 3) yields the indices of the `a` where the condition is true. >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> a > 3 array([[False, False, False], [ True, True, True], [ True, True, True]]) >>> np.nonzero(a > 3) (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) Using this result to index `a` is equivalent to using the mask directly: >>> a[np.nonzero(a > 3)] array([4, 5, 6, 7, 8, 9]) >>> a[a > 3] # prefer this spelling array([4, 5, 6, 7, 8, 9]) ``nonzero`` can also be called as a method of the array. >>> (a > 3).nonzero() (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) obj2sctype(rep, default=None) Return the scalar dtype or NumPy equivalent of Python type of an object. Parameters ---------- rep : any The object of which the type is returned. default : any, optional If given, this is returned for objects whose types can not be determined. If not given, None is returned for those objects. Returns ------- dtype : dtype or Python type The data type of `rep`. See Also -------- sctype2char, issctype, issubsctype, issubdtype, maximum_sctype Examples -------- >>> np.obj2sctype(np.int32) <class 'numpy.int32'> >>> np.obj2sctype(np.array([1., 2.])) <class 'numpy.float64'> >>> np.obj2sctype(np.array([1.j])) <class 'numpy.complex128'> >>> np.obj2sctype(dict) <class 'numpy.object_'> >>> np.obj2sctype('string') >>> np.obj2sctype(1, default=list) <class 'list'> ones(shape, dtype=None, order='C', *, like=None) Return a new array of given shape and type, filled with ones. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired 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. like : array_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. .. versionadded:: 1.20.0 Returns ------- out : ndarray Array of ones with the given shape, dtype, and order. See Also -------- ones_like : Return an array of ones with shape and type of input. empty : Return a new uninitialized array. zeros : Return a new array setting values to zero. full : Return a new array of given shape filled with value. Examples -------- >>> np.ones(5) array([1., 1., 1., 1., 1.]) >>> np.ones((5,), dtype=int) array([1, 1, 1, 1, 1]) >>> np.ones((2, 1)) array([[1.], [1.]]) >>> s = (2,2) >>> np.ones(s) array([[1., 1.], [1., 1.]]) ones_like(a, dtype=None, order='K', subok=True, shape=None) Return an array of ones with the same shape and type as a given array. Parameters ---------- a : array_like The shape and data-type of `a` define these same attributes of the returned array. dtype : data-type, optional Overrides the data type of the result. .. versionadded:: 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 `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. .. versionadded:: 1.6.0 subok : bool, 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. shape : int 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. .. versionadded:: 1.17.0 Returns ------- out : ndarray Array of ones with the same shape and type as `a`. See Also -------- empty_like : Return an empty array 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. ones : Return a new array setting values to one. Examples -------- >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> x array([[0, 1, 2], [3, 4, 5]]) >>> np.ones_like(x) array([[1, 1, 1], [1, 1, 1]]) >>> y = np.arange(3, dtype=float) >>> y array([0., 1., 2.]) >>> np.ones_like(y) array([1., 1., 1.]) outer(a, b, out=None) Compute the outer product of two vectors. Given two vectors, ``a = [a0, a1, ..., aM]`` and ``b = [b0, b1, ..., bN]``, the outer product [1]_ is:: [[a0*b0 a0*b1 ... a0*bN ] [a1*b0 . [ ... . [aM*b0 aM*bN ]] Parameters ---------- a : (M,) array_like First input vector. Input is flattened if not already 1-dimensional. b : (N,) array_like Second input vector. Input is flattened if not already 1-dimensional. out : (M, N) ndarray, optional A location where the result is stored .. versionadded:: 1.9.0 Returns ------- out : (M, N) ndarray ``out[i, j] = a[i] * b[j]`` See also -------- inner einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent. ufunc.outer : A generalization to dimensions other than 1D and other operations. ``np.multiply.outer(a.ravel(), b.ravel())`` is the equivalent. tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))`` is the equivalent. References ---------- .. [1] : G. H. Golub and C. F. Van Loan, *Matrix Computations*, 3rd ed., Baltimore, MD, Johns Hopkins University Press, 1996, pg. 8. Examples -------- Make a (*very* coarse) grid for computing a Mandelbrot set: >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5)) >>> rl array([[-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.], [-2., -1., 0., 1., 2.]]) >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,))) >>> im array([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j], [0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j], [0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) >>> grid = rl + im >>> grid array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j], [-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j], [-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j], [-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j], [-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]]) An example using a "vector" of letters: >>> x = np.array(['a', 'b', 'c'], dtype=object) >>> np.outer(x, [1, 2, 3]) array([['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']], dtype=object) packbits(...) packbits(a, axis=None, bitorder='big') Packs the elements of a binary-valued array into bits in a uint8 array. The result is padded to full bytes by inserting zero bits at the end. Parameters ---------- a : array_like An array of integers or booleans whose elements should be packed to bits. axis : int, optional The dimension over which bit-packing is done. ``None`` implies packing the flattened array. bitorder : {'big', 'little'}, optional The order of the input bits. 'big' will mimic bin(val), ``[0, 0, 0, 0, 0, 0, 1, 1] => 3 = 0b00000011``, 'little' will reverse the order so ``[1, 1, 0, 0, 0, 0, 0, 0] => 3``. Defaults to 'big'. .. versionadded:: 1.17.0 Returns ------- packed : ndarray Array of type uint8 whose elements represent bits corresponding to the logical (0 or nonzero) value of the input elements. The shape of `packed` has the same number of dimensions as the input (unless `axis` is None, in which case the output is 1-D). See Also -------- unpackbits: Unpacks elements of a uint8 array into a binary-valued output array. Examples -------- >>> a = np.array([[[1,0,1], ... [0,1,0]], ... [[1,1,0], ... [0,0,1]]]) >>> b = np.packbits(a, axis=-1) >>> b array([[[160], [ 64]], [[192], [ 32]]], dtype=uint8) Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000, and 32 = 0010 0000. pad(array, pad_width, mode='constant', **kwargs) Pad an array. Parameters ---------- array : array_like of rank N The array to pad. pad_width : {sequence, array_like, int} Number of values padded to the edges of each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes. mode : str or function, optional One of the following string values or a user supplied function. 'constant' (default) Pads with a constant value. 'edge' Pads with the edge values of array. 'linear_ramp' Pads with the linear ramp between end_value and the array edge value. 'maximum' Pads with the maximum value of all or part of the vector along each axis. 'mean' Pads with the mean value of all or part of the vector along each axis. 'median' Pads with the median value of all or part of the vector along each axis. 'minimum' Pads with the minimum value of all or part of the vector along each axis. 'reflect' Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis. 'symmetric' Pads with the reflection of the vector mirrored along the edge of the array. 'wrap' Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning. 'empty' Pads with undefined values. .. versionadded:: 1.17 <function> Padding function, see Notes. stat_length : sequence or int, optional Used in 'maximum', 'mean', 'median', and 'minimum'. Number of values at edge of each axis used to calculate the statistic value. ((before_1, after_1), ... (before_N, after_N)) unique statistic lengths for each axis. ((before, after),) yields same before and after statistic lengths for each axis. (stat_length,) or int is a shortcut for before = after = statistic length for all axes. Default is ``None``, to use the entire axis. constant_values : sequence or scalar, optional Used in 'constant'. The values to set the padded values for each axis. ``((before_1, after_1), ... (before_N, after_N))`` unique pad constants for each axis. ``((before, after),)`` yields same before and after constants for each axis. ``(constant,)`` or ``constant`` is a shortcut for ``before = after = constant`` for all axes. Default is 0. end_values : sequence or scalar, optional Used in 'linear_ramp'. The values used for the ending value of the linear_ramp and that will form the edge of the padded array. ``((before_1, after_1), ... (before_N, after_N))`` unique end values for each axis. ``((before, after),)`` yields same before and after end values for each axis. ``(constant,)`` or ``constant`` is a shortcut for ``before = after = constant`` for all axes. Default is 0. reflect_type : {'even', 'odd'}, optional Used in 'reflect', and 'symmetric'. The 'even' style is the default with an unaltered reflection around the edge value. For the 'odd' style, the extended part of the array is created by subtracting the reflected values from two times the edge value. Returns ------- pad : ndarray Padded array of rank equal to `array` with shape increased according to `pad_width`. Notes ----- .. versionadded:: 1.7.0 For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previous axes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated by using padded values from the first axis. The padding function, if used, should modify a rank 1 array in-place. It has the following signature:: padding_func(vector, iaxis_pad_width, iaxis, kwargs) where vector : ndarray A rank 1 array already padded with zeros. Padded values are vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:]. iaxis_pad_width : tuple A 2-tuple of ints, iaxis_pad_width[0] represents the number of values padded at the beginning of vector where iaxis_pad_width[1] represents the number of values padded at the end of vector. iaxis : int The axis currently being calculated. kwargs : dict Any keyword arguments the function requires. Examples -------- >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6)) array([4, 4, 1, ..., 6, 6, 6]) >>> np.pad(a, (2, 3), 'edge') array([1, 1, 1, ..., 5, 5, 5]) >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4)) array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4]) >>> np.pad(a, (2,), 'maximum') array([5, 5, 1, 2, 3, 4, 5, 5, 5]) >>> np.pad(a, (2,), 'mean') array([3, 3, 1, 2, 3, 4, 5, 3, 3]) >>> np.pad(a, (2,), 'median') array([3, 3, 1, 2, 3, 4, 5, 3, 3]) >>> a = [[1, 2], [3, 4]] >>> np.pad(a, ((3, 2), (2, 3)), 'minimum') array([[1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [3, 3, 3, 4, 3, 3, 3], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1]]) >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'reflect') array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2]) >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd') array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> np.pad(a, (2, 3), 'symmetric') array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3]) >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd') array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7]) >>> np.pad(a, (2, 3), 'wrap') array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3]) >>> def pad_with(vector, pad_width, iaxis, kwargs): ... pad_value = kwargs.get('padder', 10) ... vector[:pad_width[0]] = pad_value ... vector[-pad_width[1]:] = pad_value >>> a = np.arange(6) >>> a = a.reshape((2, 3)) >>> np.pad(a, 2, pad_with) array([[10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 0, 1, 2, 10, 10], [10, 10, 3, 4, 5, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10]]) >>> np.pad(a, 2, pad_with, padder=100) array([[100, 100, 100, 100, 100, 100, 100], [100, 100, 100, 100, 100, 100, 100], [100, 100, 0, 1, 2, 100, 100], [100, 100, 3, 4, 5, 100, 100], [100, 100, 100, 100, 100, 100, 100], [100, 100, 100, 100, 100, 100, 100]]) partition(a, kth, axis=-1, kind='introselect', order=None) Return a partitioned copy of an array. Creates a copy of the array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined. .. versionadded:: 1.8.0 Parameters ---------- a : array_like Array to be sorted. kth : int or sequence of ints Element index to partition by. The k-th value of the element will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. The order of all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all elements indexed by k-th of them into their sorted position at once. axis : int or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'introselect'}, optional Selection algorithm. Default is 'introselect'. order : str or list of str, optional When `a` is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string. Not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. Returns ------- partitioned_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.partition : Method to sort an array in-place. argpartition : Indirect partition. sort : Full sorting Notes ----- The various selection algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The available algorithms have the following properties: ================= ======= ============= ============ ======= kind speed worst case work space stable ================= ======= ============= ============ ======= 'introselect' 1 O(n) 0 no ================= ======= ============= ============ ======= All the partition algorithms make temporary copies of the data when partitioning along any but the last axis. Consequently, partitioning along the last axis is faster and uses less space than partitioning along any other axis. The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. Examples -------- >>> a = np.array([3, 4, 2, 1]) >>> np.partition(a, 3) array([2, 1, 3, 4]) >>> np.partition(a, (1, 3)) array([1, 2, 3, 4]) percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False) Compute the q-th percentile of the data along the specified axis. Returns the q-th percentile(s) of the array elements. Parameters ---------- a : array_like Input array or object that can be converted to an array. q : array_like of float Percentile or sequence of percentiles to compute, which must be between 0 and 100 inclusive. axis : {int, tuple of int, None}, optional Axis or axes along which the percentiles are computed.

๐Ÿ”ง FUNCTIONS

๐Ÿ“– percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False)

Compute the q-th percentile of the data along the specified axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

percentile : scalar or ndarray โ€” If q is a single percentile and axis=None, then the result is a scalar. If multiple percentiles are given, first axis of the result corresponds to the percentiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.

๐Ÿ” See Also

mean, median (equivalent to percentile(..., 50)), nanpercentile, quantile (equivalent to percentile, except with q in the range [0, 1]).

๐Ÿ’ก Notes

Given a vector V of length N, the q-th percentile of V is the value q/100 of the way from the minimum to the maximum in a sorted copy of V. The values and distances of the two nearest neighbors as well as the interpolation parameter will determine the percentile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=50, the same as the minimum if q=0 and the same as the maximum if q=100.

๐Ÿ“ Examples

>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10,  7,  4],
       [ 3,  2,  1]])
>>> np.percentile(a, 50)
3.5
>>> np.percentile(a, 50, axis=0)
array([6.5, 4.5, 2.5])
>>> np.percentile(a, 50, axis=1)
array([7.,  2.])
>>> np.percentile(a, 50, axis=1, keepdims=True)
array([[7.],
       [2.]])

>>> m = np.percentile(a, 50, axis=0)
>>> out = np.zeros_like(m)
>>> np.percentile(a, 50, axis=0, out=out)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])

>>> b = a.copy()
>>> np.percentile(b, 50, axis=1, overwrite_input=True)
array([7.,  2.])
>>> assert not np.all(a == b)

๐Ÿ“– piecewise(x, condlist, funclist, *args, **kw)

Evaluate a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray โ€” The output is the same shape and type as x and is found by calling the functions in funclist on the appropriate portions of x, as defined by the boolean arrays in condlist. Portions not covered by any condition have a default value of 0.

๐Ÿ” See Also

choose, select, where

๐Ÿ’ก Notes

This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corresponding condition from condlist. The result is:

    |--
    |funclist[0](x[condlist[0]])
out = |funclist[1](x[condlist[1]])
    |...
    |funclist[n2](x[condlist[n2]])
    |--

๐Ÿ“ Examples

>>> x = np.linspace(-2.5, 2.5, 6)
>>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
array([-1., -1., -1.,  1.,  1.,  1.])

>>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
array([2.5,  1.5,  0.5,  0.5,  1.5,  2.5])

>>> y = -2
>>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])
array(2)

๐Ÿ“– place(arr, mask, vals)

Change elements of an array based on conditional and input values. Similar to np.copyto(arr, vals, where=mask), the difference is that place uses the first N elements of vals, where N is the number of True values in mask, while copyto uses the elements where mask is True. Note that extract does the exact opposite of place.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

copyto, put, take, extract

๐Ÿ“ Examples

>>> arr = np.arange(6).reshape(2, 3)
>>> np.place(arr, arr>2, [44, 55])
>>> arr
array([[ 0,  1,  2],
       [44, 55, 44]])

๐Ÿ“– poly(seq_of_zeros)

Find the coefficients of a polynomial with the given sequence of roots.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.

Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

c : ndarray โ€” 1D array of polynomial coefficients from highest to lowest degree: c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N] where c[0] always equals 1.

๐Ÿšซ Raises

ValueError โ€” If input is the wrong shape (the input must be a 1-D or square 2-D array).

๐Ÿ” See Also

polyval, roots, polyfit, poly1d

๐Ÿ’ก Notes

Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use polyfit.)

The characteristic polynomial, p_a(t), of an n-by-n matrix A is given by p_a(t) = det(t I - A), where I is the n-by-n identity matrix.

๐Ÿ“ Examples

>>> np.poly((0, 0, 0)) # Multiple root example
array([1., 0., 0., 0.])

>>> np.poly((-1./2, 0, 1./2))
array([ 1.  ,  0.  , -0.25,  0.  ])

>>> np.poly((np.random.random(1)[0], 0, np.random.random(1)[0]))
array([ 1.        , -0.77086955,  0.08618131,  0.        ]) # random

>>> P = np.array([[0, 1./3], [-1./2, 0]])
>>> np.poly(P)
array([1.        , 0.        , 0.16666667])

๐Ÿ“– polyadd(a1, a2)

Find the sum of two polynomials.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.

Returns the polynomial resulting from the sum of two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray or poly1d object โ€” The sum of the inputs. If either input is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree.

๐Ÿ” See Also

poly1d, poly, polyder, polydiv, polyfit, polyint, polysub, polyval

๐Ÿ“ Examples

>>> np.polyadd([1, 2], [9, 5, 4])
array([9, 6, 6])

>>> p1 = np.poly1d([1, 2])
>>> p2 = np.poly1d([9, 5, 4])
>>> print(p1)
1 x + 2
>>> print(p2)
   2
9 x + 5 x + 4
>>> print(np.polyadd(p1, p2))
   2
9 x + 6 x + 6

๐Ÿ“– polyder(p, m=1)

Return the derivative of the specified order of a polynomial.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

der : poly1d โ€” A new polynomial representing the derivative.

๐Ÿ” See Also

polyint, poly1d

๐Ÿ“ Examples

>>> p = np.poly1d([1,1,1,1])
>>> p2 = np.polyder(p)
>>> p2
poly1d([3, 2, 1])

>>> p2(2.)
17.0

>>> (p(2. + 0.001) - p(2.)) / 0.001
17.007000999997857

>>> np.polyder(p, 2)
poly1d([6, 2])
>>> np.polyder(p, 3)
poly1d([6])
>>> np.polyder(p, 4)
poly1d([0])

๐Ÿ“– polydiv(u, v)

Returns the quotient and remainder of polynomial division.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.

The input arrays are the coefficients (including any coefficients equal to zero) of the "numerator" (dividend) and "denominator" (divisor) polynomials, respectively.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ” See Also

poly, polyadd, polyder, polyfit, polyint, polymul, polysub, polyval

๐Ÿ’ก Notes

Both u and v must be 0-d or 1-d (ndim = 0 or 1), but u.ndim need not equal v.ndim. In other words, all four possible combinations - u.ndim = v.ndim = 0, u.ndim = v.ndim = 1, u.ndim = 1, v.ndim = 0, and u.ndim = 0, v.ndim = 1 - work.

๐Ÿ“ Examples

>>> x = np.array([3.0, 5.0, 2.0])
>>> y = np.array([2.0, 1.0])
>>> np.polydiv(x, y)
(array([1.5 , 1.75]), array([0.25]))

๐Ÿ“– polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)

Least squares polynomial fit.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. The Polynomial.fit class method is recommended for new code as it is more stable numerically.

Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimises the squared error in the order deg, deg-1, ... 0.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Warns

RankWarning โ€” The rank of the coefficient matrix in the least-squares fit is deficient. The warning is only raised if full = False. The warnings can be turned off by warnings.simplefilter('ignore', np.RankWarning).

๐Ÿ” See Also

polyval, linalg.lstsq, scipy.interpolate.UnivariateSpline

๐Ÿ’ก Notes

The solution minimizes the squared error E = sum_j |p(x_j) - y_j|^2 in the equations:

x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]
...
x[k]**n * p[0] + ... + x[k] * p[n-1] + p[k] = y[k]

The coefficient matrix of the coefficients p is a Vandermonde matrix. polyfit issues a RankWarning when the least-squares fit is badly conditioned. This implies that the best fit is not well-defined due to numerical error. The results may be improved by lowering the polynomial degree or by replacing x by x - x.mean(). The rcond parameter can also be set to a value smaller than its default, but the resulting fit may be spurious. Note that fitting polynomial coefficients is inherently badly conditioned when the degree of the polynomial is large or the interval of sample points is badly centered. When polynomial fits are not satisfactory, splines may be a good alternative.

๐Ÿ“ Examples

>>> import warnings
>>> x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
>>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
>>> z = np.polyfit(x, y, 3)
>>> z
array([ 0.08703704, -0.81349206,  1.69312169, -0.03968254]) # may vary

>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179 # may vary
>>> p(3.5)
-0.34732142857143039 # may vary
>>> p(10)
22.579365079365115 # may vary

>>> with warnings.catch_warnings():
...     warnings.simplefilter('ignore', np.RankWarning)
...     p30 = np.poly1d(np.polyfit(x, y, 30))
...
>>> p30(4)
-0.80000000000000204 # may vary
>>> p30(5)
-0.99999999999999445 # may vary
>>> p30(4.5)
-0.10547061179440398 # may vary

>>> import matplotlib.pyplot as plt
>>> xp = np.linspace(-2, 6, 100)
>>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
>>> plt.ylim(-2,2)
(-2, 2)
>>> plt.show()

๐Ÿ“– polyint(p, m=1, k=None)

Return an antiderivative (indefinite integral) of a polynomial.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.

The returned order m antiderivative P of polynomial p satisfies d^m/dx^m P(x) = p(x) and is defined up to m - 1 integration constants k.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

polyder, poly1d.integ

๐Ÿ“ Examples

>>> p = np.poly1d([1,1,1])
>>> P = np.polyint(p)
>>> P
 poly1d([ 0.33333333,  0.5       ,  1.        ,  0.        ]) # may vary
>>> np.polyder(P) == p
True

>>> P = np.polyint(p, 3)
>>> P(0)
0.0
>>> np.polyder(P)(0)
0.0
>>> np.polyder(P, 2)(0)
0.0
>>> P = np.polyint(p, 3, k=[6,5,3])
>>> P
poly1d([ 0.01666667,  0.04166667,  0.16666667,  3. ,  5. ,  3. ]) # may vary

>>> np.polyder(P, 2)(0)
6.0
>>> np.polyder(P, 1)(0)
5.0
>>> P(0)
3.0

๐Ÿ“– polymul(a1, a2)

Find the product of two polynomials.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.

Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray or poly1d object โ€” The polynomial resulting from the multiplication of the inputs. If either inputs is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree.

๐Ÿ” See Also

poly1d, poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval, convolve

๐Ÿ“ Examples

>>> np.polymul([1, 2, 3], [9, 5, 1])
array([ 9, 23, 38, 17,  3])

>>> p1 = np.poly1d([1, 2, 3])
>>> p2 = np.poly1d([9, 5, 1])
>>> print(p1)
   2
1 x + 2 x + 3
>>> print(p2)
   2
9 x + 5 x + 1
>>> print(np.polymul(p1, p2))
   4      3      2
9 x + 23 x + 38 x + 17 x + 3

๐Ÿ“– polysub(a1, a2)

Difference (subtraction) of two polynomials.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.

Given two polynomials a1 and a2, returns a1 - a2. a1 and a2 can be either array_like sequences of the polynomials' coefficients (including coefficients equal to zero), or poly1d objects.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray or poly1d โ€” Array or poly1d object of the difference polynomial's coefficients.

๐Ÿ” See Also

polyval, polydiv, polymul, polyadd

๐Ÿ“ Examples

>>> np.polysub([2, 10, -2], [3, 10, -4])
array([-1,  0,  2])

๐Ÿ“– polyval(p, x)

Evaluate a polynomial at specific values.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.

If p is of length N, this function returns the value: p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]. If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite polynomial p(x(t)) is returned.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

values : ndarray or poly1d โ€” If x is a poly1d instance, the result is the composition of the two polynomials, i.e., x is "substituted" in p and the simplified result is returned. In addition, the type of x - array_like or poly1d - governs the type of the output: x array_like => values array_like, x a poly1d object => values is also.

๐Ÿ” See Also

poly1d

๐Ÿ’ก Notes

Horner's scheme is used to evaluate the polynomial. Even so, for polynomials of high degree the values may be inaccurate due to rounding errors. Use carefully. If x is a subtype of ndarray the return value will be of the same type.

๐Ÿ“ Examples

>>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
76
>>> np.polyval([3,0,1], np.poly1d(5))
poly1d([76])
>>> np.polyval(np.poly1d([3,0,1]), 5)
76
>>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
poly1d([76])

๐Ÿ“– printoptions(*args, **kwargs)

Context manager for setting print options. Set print options for the scope of the with block, and restore the old options at the end. See set_printoptions for the full description of available options.

๐Ÿ“ Examples

>>> from numpy.testing import assert_equal
>>> with np.printoptions(precision=2):
...     np.array([2.0]) / 3
array([0.67])

>>> with np.printoptions(precision=2) as opts:
...      assert_equal(opts, np.get_printoptions())

๐Ÿ” See Also

set_printoptions, get_printoptions


๐Ÿ“– prod(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Return the product of array elements over a given axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

product_along_axis : ndarray โ€” An array shaped as a but with the specified axis removed. Returns a reference to out if specified.

๐Ÿ” See Also

ndarray.prod, ufuncs-output-type

๐Ÿ’ก Notes

Arithmetic is modular when using integer types, and no error is raised on overflow. The product of an empty array is the neutral element 1.

๐Ÿ“ Examples

>>> np.prod([1.,2.])
2.0

>>> np.prod([[1.,2.],[3.,4.]])
24.0

>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([  2.,  12.])

>>> np.prod([1., np.nan, 3.], where=[True, False, True])
3.0

>>> x = np.array([1, 2, 3], dtype=np.uint8)
>>> np.prod(x).dtype == np.uint
True

>>> x = np.array([1, 2, 3], dtype=np.int8)
>>> np.prod(x).dtype == int
True

>>> np.prod([1, 2], initial=5)
10

๐Ÿ“– product(*args, **kwargs)

Return the product of array elements over a given axis.

๐Ÿ” See Also

prod : equivalent function; see for details.


๐Ÿ“– promote_types(type1, type2)

Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 may be safely cast. The returned data type is always in native byte order. This function is symmetric, but rarely associative.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : dtype โ€” The promoted data type.

๐Ÿ’ก Notes

๐Ÿ†• Added in version 1.6.0. Starting in NumPy 1.9, promote_types function now returns a valid string length when given an integer or float dtype as one argument and a string dtype as another argument.

๐Ÿ” See Also

result_type, dtype, can_cast

๐Ÿ“ Examples

>>> np.promote_types('f4', 'f8')
dtype('float64')

>>> np.promote_types('i8', 'f4')
dtype('float64')

>>> np.promote_types('>i8', '<c8')
dtype('complex128')

>>> np.promote_types('i4', 'S8')
dtype('S11')

>>> p = np.promote_types
>>> p('S', p('i1', 'u1'))
dtype('S6')
>>> p(p('S', 'i1'), 'u1')
dtype('S4')

๐Ÿ“– ptp(a, axis=None, out=None, keepdims=<no value>)

Range of values (maximum - minimum) along an axis. The name of the function comes from the acronym for 'peak to peak'.

โš ๏ธ ptp preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. np.int8, np.int16, etc) is also a signed integer with n bits. In that case, peak-to-peak values greater than 2**(n-1)-1 will be returned as negative values.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

ptp : ndarray โ€” A new array holding the result, unless out was specified, in which case a reference to out is returned.

๐Ÿ“ Examples

>>> x = np.array([[4, 9, 2, 10],
...               [6, 9, 7, 12]])

>>> np.ptp(x, axis=1)
array([8, 6])

>>> np.ptp(x, axis=0)
array([2, 0, 5, 2])

>>> np.ptp(x)
10

>>> y = np.array([[1, 127],
...               [0, 127],
...               [-1, 127],
...               [-2, 127]], dtype=np.int8)
>>> np.ptp(y, axis=1)
array([ 126,  127, -128, -127], dtype=int8)

>>> np.ptp(y, axis=1).view(np.uint8)
array([126, 127, 128, 129], dtype=uint8)

๐Ÿ“– put(a, ind, v, mode='raise')

Replaces specified elements of an array with given values. The indexing works on the flattened target array. put is roughly equivalent to: a.flat[ind] = v.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

putmask, place, put_along_axis

๐Ÿ“ Examples

>>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44,   1, -55,   3,   4])

>>> a = np.arange(5)
>>> np.put(a, 22, -5, mode='clip')
>>> a
array([ 0,  1,  2,  3, -5])

๐Ÿ“– put_along_axis(arr, indices, values, axis)

Put values into the destination array by matching 1d index and data slices. This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to place values into the latter. These slices can be different lengths. Functions returning an index along an axis, like argsort and argpartition, produce suitable indices for this function.

๐Ÿ†• Added in version 1.15.0.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

take_along_axis

๐Ÿ“ Examples

>>> a = np.array([[10, 30, 20], [60, 40, 50]])
>>> ai = np.expand_dims(np.argmax(a, axis=1), axis=1)
>>> ai
array([[1],
       [0]])
>>> np.put_along_axis(a, ai, 99, axis=1)
>>> a
array([[10, 99, 20],
       [99, 40, 50]])

๐Ÿ“– putmask(a, mask, values)

Changes elements of an array based on conditional and input values. Sets a.flat[n] = values[n] for each n where mask.flat[n]==True. If values is not the same size as a and mask then it will repeat. This gives behavior different from a[mask] = values.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

place, put, take, copyto

๐Ÿ“ Examples

>>> x = np.arange(6).reshape(2, 3)
>>> np.putmask(x, x>2, x**2)
>>> x
array([[ 0,  1,  2],
       [ 9, 16, 25]])

>>> x = np.arange(5)
>>> np.putmask(x, x>1, [-33, -44])
>>> x
array([  0,   1, -33, -44, -33])

๐Ÿ“– quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False)

Compute the q-th quantile of the data along the specified axis.

๐Ÿ†• Added in version 1.15.0.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

quantile : scalar or ndarray โ€” If q is a single quantile and axis=None, then the result is a scalar. If multiple quantiles are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.

๐Ÿ” See Also

mean, percentile (equivalent to quantile, but with q in the range [0, 100]), median (equivalent to quantile(..., 0.5)), nanquantile

๐Ÿ’ก Notes

Given a vector V of length N, the q-th quantile of V is the value q of the way from the minimum to the maximum in a sorted copy of V. The values and distances of the two nearest neighbors as well as the interpolation parameter will determine the quantile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=0.5, the same as the minimum if q=0.0 and the same as the maximum if q=1.0.

๐Ÿ“ Examples

>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10,  7,  4],
       [ 3,  2,  1]])
>>> np.quantile(a, 0.5)
3.5
>>> np.quantile(a, 0.5, axis=0)
array([6.5, 4.5, 2.5])
>>> np.quantile(a, 0.5, axis=1)
array([7.,  2.])
>>> np.quantile(a, 0.5, axis=1, keepdims=True)
array([[7.],
       [2.]])
>>> m = np.quantile(a, 0.5, axis=0)
>>> out = np.zeros_like(m)
>>> np.quantile(a, 0.5, axis=0, out=out)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])
>>> b = a.copy()
>>> np.quantile(b, 0.5, axis=1, overwrite_input=True)
array([7.,  2.])
>>> assert not np.all(a == b)

๐Ÿ“– ravel(a, order='C')

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned. A copy is made only if needed. As of NumPy 1.10, the returned array will have the same type as the input array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

y : array_like โ€” y is an array of the same subtype as a, with shape (a.size,). Note that matrices are special cased for backward compatibility, if a is a matrix, then y is a 1-D ndarray.

๐Ÿ” See Also

ndarray.flat, ndarray.flatten, ndarray.reshape

๐Ÿ’ก Notes

In row-major, C-style order, in two dimensions, the row index varies the slowest, and the column index the quickest. This can be generalized to multiple dimensions, where row-major order implies that the index along the first axis varies slowest, and the index along the last quickest. The opposite holds for column-major, Fortran-style index ordering. When a view is desired in as many cases as possible, arr.reshape(-1) may be preferable.

๐Ÿ“ Examples

>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.ravel(x)
array([1, 2, 3, 4, 5, 6])

>>> x.reshape(-1)
array([1, 2, 3, 4, 5, 6])

>>> np.ravel(x, order='F')
array([1, 4, 2, 5, 3, 6])

>>> np.ravel(x.T)
array([1, 4, 2, 5, 3, 6])
>>> np.ravel(x.T, order='A')
array([1, 2, 3, 4, 5, 6])

>>> a = np.arange(3)[::-1]; a
array([2, 1, 0])
>>> a.ravel(order='C')
array([2, 1, 0])
>>> a.ravel(order='K')
array([2, 1, 0])

>>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
array([[[ 0,  2,  4],
        [ 1,  3,  5]],
       [[ 6,  8, 10],
        [ 7,  9, 11]]])
>>> a.ravel(order='C')
array([ 0,  2,  4,  1,  3,  5,  6,  8, 10,  7,  9, 11])
>>> a.ravel(order='K')
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

๐Ÿ“– ravel_multi_index(multi_index, dims, mode='raise', order='C')

Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

raveled_indices : ndarray โ€” An array of indices into the flattened version of an array of dimensions dims.

๐Ÿ” See Also

unravel_index

๐Ÿ’ก Notes

๐Ÿ†• Added in version 1.6.0.

๐Ÿ“ Examples

>>> arr = np.array([[3,6,6],[4,5,1]])
>>> np.ravel_multi_index(arr, (7,6))
array([22, 41, 37])
>>> np.ravel_multi_index(arr, (7,6), order='F')
array([31, 41, 13])
>>> np.ravel_multi_index(arr, (4,6), mode='clip')
array([22, 23, 19])
>>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
array([12, 13, 13])

>>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
1621

๐Ÿ“– real(val)

Return the real part of the complex argument.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray or scalar โ€” The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float.

๐Ÿ” See Also

real_if_close, imag, angle

๐Ÿ“ Examples

>>> a = np.array([1+2j, 3+4j, 5+6j])
>>> a.real
array([1.,  3.,  5.])
>>> a.real = 9
>>> a
array([9.+2.j,  9.+4.j,  9.+6.j])
>>> a.real = np.array([9, 8, 7])
>>> a
array([9.+2.j,  8.+4.j,  7.+6.j])
>>> np.real(1 + 1j)
1.0

๐Ÿ“– real_if_close(a, tol=100)

If input is complex with all imaginary parts close to zero, return real parts. "Close to zero" is defined as tol * (machine epsilon of the type for a).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray โ€” If a is real, the type of a is used for the output. If a has complex elements, the returned type is float.

๐Ÿ” See Also

real, imag, angle

๐Ÿ’ก Notes

Machine epsilon varies from machine to machine and between data types but Python floats on most platforms have a machine epsilon equal to 2.2204460492503131e-16. You can use np.finfo(float).eps to print out the machine epsilon for floats.

๐Ÿ“ Examples

>>> np.finfo(float).eps
2.2204460492503131e-16 # may vary

>>> np.real_if_close([2.1 + 4e-14j, 5.2 + 3e-15j], tol=1000)
array([2.1, 5.2])
>>> np.real_if_close([2.1 + 4e-13j, 5.2 + 3e-15j], tol=1000)
array([2.1+4.e-13j, 5.2 + 3e-15j])

๐Ÿ“– recfromcsv(fname, **kwargs)

Load ASCII data stored in a comma-separated file. The returned array is a record array (if usemask=False, see recarray) or a masked record array (if usemask=True, see ma.mrecords.MaskedRecords).

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

numpy.genfromtxt

๐Ÿ’ก Notes

By default, dtype is None, which means that the data-type of the output array will be determined from the data.


๐Ÿ“– recfromtxt(fname, **kwargs)

Load ASCII data from a file and return it in a record array. If usemask=False a standard recarray is returned, if usemask=True a MaskedRecords array is returned.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

numpy.genfromtxt

๐Ÿ’ก Notes

By default, dtype is None, which means that the data-type of the output array will be determined from the data.


๐Ÿ“– repeat(a, repeats, axis=None)

Repeat elements of an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

repeated_array : ndarray โ€” Output array which has the same shape as a, except along the given axis.

๐Ÿ” See Also

tile, unique

๐Ÿ“ Examples

>>> np.repeat(3, 4)
array([3, 3, 3, 3])
>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
>>> np.repeat(x, 3, axis=1)
array([[1, 1, 1, 2, 2, 2],
       [3, 3, 3, 4, 4, 4]])
>>> np.repeat(x, [1, 2], axis=0)
array([[1, 2],
       [3, 4],
       [3, 4]])

๐Ÿ“– require(a, dtype=None, requirements=None, *, like=None)

Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray โ€” Array with specified requirements and type if given.

๐Ÿ” See Also

asarray, asanyarray, ascontiguousarray, asfortranarray, ndarray.flags

๐Ÿ’ก Notes

The returned array will be guaranteed to have the listed requirements by making a copy if needed.

๐Ÿ“ Examples

>>> x = np.arange(6).reshape(2,3)
>>> x.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

>>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
>>> y.flags
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

๐Ÿ“– reshape(a, newshape, order='C')

Gives a new shape to an array without changing its data.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

reshaped_array : ndarray โ€” This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the *memory layout* (C- or Fortran- contiguous) of the returned array.

๐Ÿ” See Also

ndarray.reshape

๐Ÿ’ก Notes

It is not always possible to change the shape of an array without copying the data. If you want an error to be raised when the data is copied, you should assign the new shape to the shape attribute of the array. The order keyword gives the index ordering both for fetching the values from a, and then placing the values into the output array.

๐Ÿ“ Examples

>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])
>>> np.reshape(a, 6, order='F')
array([1, 4, 2, 5, 3, 6])

>>> np.reshape(a, (3,-1))       # the unspecified value is inferred to be 2
array([[1, 2],
       [3, 4],
       [5, 6]])

๐Ÿ“– resize(a, new_shape)

Return a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of a. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

reshaped_array : ndarray โ€” The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order.

๐Ÿ” See Also

np.reshape, np.pad, np.repeat, ndarray.resize

๐Ÿ’ก Notes

When the total size of the array does not change ~numpy.reshape should be used. In most other cases either indexing (to reduce the size) or padding (to increase the size) may be a more appropriate solution. Warning: This functionality does **not** consider axes separately, i.e. it does not apply interpolation/extrapolation. It fills the return array with the required number of elements, iterating over a in C-order, disregarding axes (and cycling back from the start if the new shape is larger). This functionality is therefore not suitable to resize images, or data where each axis represents a separate and distinct entity.

๐Ÿ“ Examples

>>> a=np.array([[0,1],[2,3]])
>>> np.resize(a,(2,3))
array([[0, 1, 2],
       [3, 0, 1]])
>>> np.resize(a,(1,4))
array([[0, 1, 2, 3]])
>>> np.resize(a,(2,4))
array([[0, 1, 2, 3],
       [0, 1, 2, 3]])

๐Ÿ“– result_type(*arrays_and_dtypes)

Returns the type that results from applying the NumPy type promotion rules to the arguments. Type promotion in NumPy works similarly to the rules in languages like C++, with some slight differences. When both scalars and arrays are used, the array's type takes precedence and the actual value of the scalar is taken into account.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : dtype โ€” The result type.

๐Ÿ” See also

dtype, promote_types, min_scalar_type, can_cast

๐Ÿ’ก Notes

๐Ÿ†• Added in version 1.6.0. The specific algorithm used is as follows: Categories are determined by first checking which of boolean, integer (int/uint), or floating point (float/complex) the maximum kind of all the arrays and the scalars are. If there are only scalars or the maximum category of the scalars is higher than the maximum category of the arrays, the data types are combined with promote_types to produce the return value. Otherwise, min_scalar_type is called on each array, and the resulting data types are all combined with promote_types to produce the return value. The set of int values is not a subset of the uint values for types with the same number of bits, something not reflected in min_scalar_type, but handled as a special case in result_type.

๐Ÿ“ Examples

>>> np.result_type(3, np.arange(7, dtype='i1'))
dtype('int8')

>>> np.result_type('i4', 'c8')
dtype('complex128')

>>> np.result_type(3.0, -2)
dtype('float64')

๐Ÿ“– roll(a, shift, axis=None)

Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

res : ndarray โ€” Output array, with the same shape as a.

๐Ÿ” See Also

rollaxis

๐Ÿ’ก Notes

๐Ÿ†• Added in version 1.12.0. Supports rolling over multiple dimensions simultaneously.

๐Ÿ“ Examples

>>> x = np.arange(10)
>>> np.roll(x, 2)
array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
>>> np.roll(x, -2)
array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])

>>> x2 = np.reshape(x, (2,5))
>>> x2
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> np.roll(x2, 1)
array([[9, 0, 1, 2, 3],
       [4, 5, 6, 7, 8]])
>>> np.roll(x2, -1)
array([[1, 2, 3, 4, 5],
       [6, 7, 8, 9, 0]])
>>> np.roll(x2, 1, axis=0)
array([[5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4]])
>>> np.roll(x2, -1, axis=0)
array([[5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4]])
>>> np.roll(x2, 1, axis=1)
array([[4, 0, 1, 2, 3],
       [9, 5, 6, 7, 8]])
>>> np.roll(x2, -1, axis=1)
array([[1, 2, 3, 4, 0],
       [6, 7, 8, 9, 5]])

๐Ÿ“– rollaxis(a, axis, start=0)

Roll the specified axis backwards, until it lies in a given position. This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11.

๐Ÿ“ฅ Parameters

startNormalized start
-(arr.ndim+1)raise AxisError
-arr.ndim0
โ‹ฎโ‹ฎ
-1arr.ndim-1
00
โ‹ฎโ‹ฎ
arr.ndimarr.ndim
arr.ndim + 1raise AxisError

๐Ÿ“ค Returns

res : ndarray โ€” For NumPy >= 1.10.0 a view of a is always returned. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned.

๐Ÿ” See Also

moveaxis, roll

๐Ÿ“ Examples

>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)
>>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)

๐Ÿ“– roots(p)

Return the roots of a polynomial with coefficients given in p.

โš ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.

The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is described by: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n].

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

out : ndarray โ€” An array containing the roots of the polynomial.

๐Ÿšซ Raises

ValueError โ€” When p cannot be converted to a rank-1 array.

๐Ÿ” See also

poly, polyval, polyfit, poly1d

๐Ÿ’ก Notes

The algorithm relies on computing the eigenvalues of the companion matrix.

๐Ÿ“ Examples

>>> coeff = [3.2, 2, 1]
>>> np.roots(coeff)
array([-0.3125+0.46351241j, -0.3125-0.46351241j])

๐Ÿ“– rot90(m, k=1, axes=(0, 1))

Rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

y : ndarray โ€” A rotated view of m.

๐Ÿ” See Also

flip, fliplr, flipud

๐Ÿ’ก Notes

rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1)); rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1)).

๐Ÿ“ Examples

>>> m = np.array([[1,2],[3,4]], int)
>>> m
array([[1, 2],
       [3, 4]])
>>> np.rot90(m)
array([[2, 4],
       [1, 3]])
>>> np.rot90(m, 2)
array([[4, 3],
       [2, 1]])
>>> m = np.arange(8).reshape((2,2,2))
>>> np.rot90(m, 1, (1,2))
array([[[1, 3],
        [0, 2]],
       [[5, 7],
        [4, 6]]])

๐Ÿ“– round_(a, decimals=0, out=None)

Round an array to the given number of decimals.

๐Ÿ” See Also

around : equivalent function; see for details.


๐Ÿ“– row_stack = vstack(tup)

Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit.

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

๐Ÿ“ค Returns

stacked : ndarray โ€” The array formed by stacking the given arrays, will be at least 2-D.

๐Ÿ” See Also

concatenate, stack, block, hstack, dstack, column_stack, vsplit

๐Ÿ“ Examples

>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
       [4, 5, 6]])

>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

๐Ÿ“– safe_eval(source)

Protected string evaluation. Evaluate a string containing a Python literal expression without allowing the execution of arbitrary non-literal code.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

obj : object โ€” The result of evaluating source.

๐Ÿšซ Raises

๐Ÿ“ Examples

>>> np.safe_eval('1')
1
>>> np.safe_eval('[1, 2, 3]')
[1, 2, 3]
>>> np.safe_eval('{"foo": ("bar", 10.0)}')
{'foo': ('bar', 10.0)}

>>> np.safe_eval('import os')
Traceback (most recent call last):
  ... SyntaxError: invalid syntax

>>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')
Traceback (most recent call last):
  ... ValueError: malformed node or string: <_ast.Call object at 0x...>

๐Ÿ“– save(file, arr, allow_pickle=True, fix_imports=True)

Save an array to a binary file in NumPy .npy format.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

savez, savetxt, load

๐Ÿ’ก Notes

For a description of the .npy format, see numpy.lib.format. Any data saved to the file is appended to the end of the file.

๐Ÿ“ Examples

>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()

>>> x = np.arange(10)
>>> np.save(outfile, x)

>>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> np.load(outfile)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


>>> with open('test.npy', 'wb') as f:
...     np.save(f, np.array([1, 2]))
...     np.save(f, np.array([1, 3]))
>>> with open('test.npy', 'rb') as f:
...     a = np.load(f)
...     b = np.load(f)
>>> print(a, b)
# [1 2] [1 3]

๐Ÿ“– savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)

Save an array to a text file.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

save, savez, savez_compressed

๐Ÿ’ก Notes

Further explanation of the fmt parameter (%[flag]width[.precision]specifier):

๐Ÿ“ Examples

>>> x = y = z = np.arange(0.0,5.0,1.0)
>>> np.savetxt('test.out', x, delimiter=',')   # X is an array
>>> np.savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays
>>> np.savetxt('test.out', x, fmt='%1.4e')   # use exponential notation

๐Ÿ“– savez(file, *args, **kwds)

Save several arrays into a single file in uncompressed .npz format. Provide arrays as keyword arguments to store them under the corresponding name in the output file: savez(fn, x=x, y=y). If arrays are specified as positional arguments, i.e., savez(fn, x, y), their names will be arr_0, arr_1, etc.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

None

๐Ÿ” See Also

save, savetxt, savez_compressed

๐Ÿ’ก Notes

The .npz file format is a zipped archive of files named after the variables they contain. The archive is not compressed and each file in the archive contains one variable in .npy format. When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the .files attribute), and for the arrays themselves. When saving dictionaries, the dictionary keys become filenames inside the ZIP archive. Therefore, keys should be valid filenames. E.g., avoid keys that begin with / or contain ..

๐Ÿ“ Examples

>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> y = np.sin(x)

>>> np.savez(outfile, x, y)
>>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> npzfile = np.load(outfile)
>>> npzfile.files
['arr_0', 'arr_1']
>>> npzfile['arr_0']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> outfile = TemporaryFile()
>>> np.savez(outfile, x=x, y=y)
>>> _ = outfile.seek(0)
>>> npzfile = np.load(outfile)
>>> sorted(npzfile.files)
['x', 'y']
>>> npzfile['x']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

๐Ÿ“– savez_compressed(file, *args, **kwds)

Save several arrays into a single file in compressed .npz format. Provide arrays as keyword arguments to store them under the corresponding name in the output file: savez(fn, x=x, y=y). If arrays are specified as positional arguments, i.e., savez(fn, x, y), their names will be arr_0, arr_1, etc.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

None

๐Ÿ” See Also

numpy.save, numpy.savetxt, numpy.savez, numpy.load

๐Ÿ’ก Notes

The .npz file format is a zipped archive of files named after the variables they contain. The archive is compressed with zipfile.ZIP_DEFLATED and each file in the archive contains one variable in .npy format. When opening the saved .npz file with load a NpzFile object is returned.

๐Ÿ“ Examples

>>> test_array = np.random.rand(3, 2)
>>> test_vector = np.random.rand(4)
>>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector)
>>> loaded = np.load('/tmp/123.npz')
>>> print(np.array_equal(test_array, loaded['a']))
True
>>> print(np.array_equal(test_vector, loaded['b']))
True

๐Ÿ“– sctype2char(sctype)

Return the string representation of a scalar dtype.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

typechar : str โ€” The string character corresponding to the scalar type.

๐Ÿšซ Raises

ValueError โ€” If sctype is an object for which the type can not be inferred.

๐Ÿ” See Also

obj2sctype, issctype, issubsctype, mintypecode

๐Ÿ“ Examples

>>> for sctype in [np.int32, np.double, np.complex_, np.string_, np.ndarray]:
...     print(np.sctype2char(sctype))
l # may vary
d
D
S
O

>>> x = np.array([1., 2-1.j])
>>> np.sctype2char(x)
'D'
>>> np.sctype2char(list)
'O'

๐Ÿ“– searchsorted(a, v, side='left', sorter=None)

Find indices where elements should be inserted to maintain order. Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

sidereturned index i satisfies
lefta[i-1] < v <= a[i]
righta[i-1] <= v < a[i]

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

indices : array of ints โ€” Array of insertion points with the same shape as v.

๐Ÿ” See Also

sort, histogram

๐Ÿ’ก Notes

Binary search is used to find the required insertion points. As of NumPy 1.4.0 searchsorted works with real/complex arrays containing nan values. The enhanced sort order is documented in sort. This function uses the same algorithm as the builtin python bisect.bisect_left (side='left') and bisect.bisect_right (side='right') functions, which is also vectorized in the v argument.

๐Ÿ“ Examples

>>> np.searchsorted([1,2,3,4,5], 3)
2
>>> np.searchsorted([1,2,3,4,5], 3, side='right')
3
>>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
array([0, 5, 1, 2])

๐Ÿ“– select(condlist, choicelist, default=0)

Return an array drawn from elements in choicelist, depending on conditions.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

output : ndarray โ€” The output at position m is the m-th element of the array in choicelist where the m-th element of the corresponding array in condlist is True.

๐Ÿ” See Also

where, take, choose, compress, diag, diagonal

๐Ÿ“ Examples

>>> x = np.arange(10)
>>> condlist = [x<3, x>5]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist)
array([ 0,  1,  2, ..., 49, 64, 81])

๐Ÿ“– set_numeric_ops(op1=func1, op2=func2, ...)

Set numerical operators for array objects.

โš ๏ธ Deprecated since version 1.16. For the general case, use PyUFunc_ReplaceLoopBySignature. For ndarray subclasses, define the __array_ufunc__ method and override the relevant ufunc.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

saved_ops : list of callables โ€” A list of all operators, stored before making replacements.

โš ๏ธ Warnings

Use with care! Incorrect usage may lead to memory errors. A function replacing an operator cannot make use of that operator. For example, when replacing add, you may not use +. Instead, directly call ufuncs.

๐Ÿ“ Examples

>>> def add_mod5(x, y):
...     return np.add(x, y) % 5
...
>>> old_funcs = np.set_numeric_ops(add=add_mod5)

>>> x = np.arange(12).reshape((3, 4))
>>> x + x
array([[0, 2, 4, 1],
       [3, 0, 2, 4],
       [1, 3, 0, 2]])

>>> ignore = np.set_numeric_ops(**old_funcs) # restore operators

๐Ÿ“– set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None)

Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

get_printoptions, printoptions, set_string_function, array2string

๐Ÿ’ก Notes

formatter is always reset with a call to set_printoptions. Use printoptions as a context manager to set the values temporarily.

๐Ÿ“ Examples

>>> np.set_printoptions(precision=4)
>>> np.array([1.123456789])
[1.1235]

>>> np.set_printoptions(threshold=5)
>>> np.arange(10)
array([0, 1, 2, ..., 7, 8, 9])

>>> eps = np.finfo(float).eps
>>> x = np.arange(4.)
>>> x**2 - (x + eps)**2
array([-4.9304e-32, -4.4409e-16,  0.0000e+00,  0.0000e+00])
>>> np.set_printoptions(suppress=True)
>>> x**2 - (x + eps)**2
array([-0., -0.,  0.,  0.])

>>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
>>> x = np.arange(3)
>>> x
array([int: 0, int: -1, int: -2])
>>> np.set_printoptions()  # formatter gets reset
>>> x
array([0, 1, 2])

>>> np.set_printoptions(edgeitems=3, infstr='inf',
... linewidth=75, nanstr='nan', precision=8,
... suppress=False, threshold=1000, formatter=None)

>>> with np.printoptions(precision=2, suppress=True, threshold=5):
...     np.linspace(0, 10, 10)
array([ 0.  ,  1.11,  2.22, ...,  7.78,  8.89, 10.  ])

๐Ÿ“– set_string_function(f, repr=True)

Set a Python function to be used when pretty printing arrays.

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

set_printoptions, get_printoptions

๐Ÿ“ Examples

>>> def pprint(arr):
...     return 'HA! - What are you going to do now?'
...
>>> np.set_string_function(pprint)
>>> a = np.arange(10)
>>> a
HA! - What are you going to do now?
>>> _ = a
>>> # [0 1 2 3 4 5 6 7 8 9]

>>> np.set_string_function(None)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> x = np.arange(4)
>>> np.set_string_function(lambda x:'random', repr=False)
>>> x.__str__()
'random'
>>> x.__repr__()
'array([0, 1, 2, 3])'

๐Ÿ“– setbufsize(size)

Set the size of the buffer used in ufuncs.

๐Ÿ“ฅ Parameters


๐Ÿ“– setdiff1d(ar1, ar2, assume_unique=False)

Find the set difference of two arrays. Return the unique values in ar1 that are not in ar2.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

setdiff1d : ndarray โ€” 1D array of values in ar1 that are not in ar2. The result is sorted when assume_unique=False, but otherwise only sorted if the input is sorted.

๐Ÿ” See Also

numpy.lib.arraysetops

๐Ÿ“ Examples

>>> a = np.array([1, 2, 3, 2, 4, 1])
>>> b = np.array([3, 4, 5, 6])
>>> np.setdiff1d(a, b)
array([1, 2])

๐Ÿ“– seterr(all=None, divide=None, over=None, under=None, invalid=None)

Set how floating-point errors are handled. Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by these settings.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

old_settings : dict โ€” Dictionary containing the old settings.

๐Ÿ” See also

seterrcall, geterr, geterrcall, errstate

๐Ÿ’ก Notes

The floating-point exceptions are defined in the IEEE 754 standard:

๐Ÿ“ Examples

>>> old_settings = np.seterr(all='ignore')  #seterr to known value
>>> np.seterr(over='raise')
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
>>> np.seterr(**old_settings)  # reset to default
{'divide': 'ignore', 'over': 'raise', 'under': 'ignore', 'invalid': 'ignore'}

>>> np.int16(32000) * np.int16(3)
30464
>>> old_settings = np.seterr(all='warn', over='raise')
>>> np.int16(32000) * np.int16(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FloatingPointError: overflow encountered in short_scalars

>>> old_settings = np.seterr(all='print')
>>> np.geterr()
{'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
>>> np.int16(32000) * np.int16(3)
30464

๐Ÿ“– seterrcall(func)

Set the floating-point error callback function or log object. There are two ways to capture floating-point error messages. The first is to set the error-handler to 'call', using seterr. Then, set the function to call using this function. The second is to set the error-handler to 'log', using seterr. Floating-point errors then trigger a call to the 'write' method of the provided object.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

h : callable, log instance or None โ€” The old error handler.

๐Ÿ” See Also

seterr, geterr, geterrcall

๐Ÿ“ Examples

>>> def err_handler(type, flag):
...     print("Floating point error (%s), with flag %s" % (type, flag))
...

>>> saved_handler = np.seterrcall(err_handler)
>>> save_err = np.seterr(all='call')

>>> np.array([1, 2, 3]) / 0.0
Floating point error (divide by zero), with flag 1
array([inf, inf, inf])

>>> np.seterrcall(saved_handler)
<function err_handler at 0x...>
>>> np.seterr(**save_err)
{'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'}

>>> class Log:
...     def write(self, msg):
...         print("LOG: %s" % msg)
...

>>> log = Log()
>>> saved_handler = np.seterrcall(log)
>>> save_err = np.seterr(all='log')

>>> np.array([1, 2, 3]) / 0.0
LOG: Warning: divide by zero encountered in true_divide
array([inf, inf, inf])

>>> np.seterrcall(saved_handler)
<numpy.core.numeric.Log object at 0x...>
>>> np.seterr(**save_err)
{'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}

๐Ÿ“– seterrobj(errobj)

Set the object that defines floating-point error handling. The error object contains all information that defines the error handling behavior in NumPy. seterrobj is used internally by the other functions that set error handling behavior (seterr, seterrcall).

๐Ÿ“ฅ Parameters

๐Ÿ” See Also

geterrobj, seterr, geterr, seterrcall, geterrcall, getbufsize, setbufsize

๐Ÿ’ก Notes

For complete documentation of the types of floating-point exceptions and treatment options, see seterr.

๐Ÿ“ Examples

>>> old_errobj = np.geterrobj()  # first get the defaults
>>> old_errobj
[8192, 521, None]

>>> def err_handler(type, flag):
...     print("Floating point error (%s), with flag %s" % (type, flag))
...
>>> new_errobj = [20000, 12, err_handler]
>>> np.seterrobj(new_errobj)
>>> np.base_repr(12, 8)  # int for divide=4 ('print') and over=1 ('warn')
'14'
>>> np.geterr()
{'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'}
>>> np.geterrcall() is err_handler
True

๐Ÿ“– setxor1d(ar1, ar2, assume_unique=False)

Find the set exclusive-or of two arrays. Return the sorted, unique values that are in only one (not both) of the input arrays.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

setxor1d : ndarray โ€” Sorted 1D array of unique values that are in only one of the input arrays.

๐Ÿ“ Examples

>>> a = np.array([1, 2, 3, 2, 4])
>>> b = np.array([2, 3, 5, 7, 5])
>>> np.setxor1d(a,b)
array([1, 4, 5, 7])

๐Ÿ“– shape(a)

Return the shape of an array.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

shape : tuple of ints โ€” The elements of the shape tuple give the lengths of the corresponding array dimensions.

๐Ÿ” See Also

len, ndarray.shape

๐Ÿ“ Examples

>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()

>>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
>>> np.shape(a)
(2,)
>>> a.shape
(2,)

๐Ÿ“– shares_memory(a, b, max_work=None)

Determine if two arrays share memory.

โš ๏ธ This function can be exponentially slow for some inputs, unless max_work is set to a finite number or MAY_SHARE_BOUNDS. If in doubt, use numpy.may_share_memory instead.

๐Ÿ“ฅ Parameters

๐Ÿšซ Raises

numpy.TooHardError โ€” Exceeded max_work.

๐Ÿ“ค Returns

out : bool

๐Ÿ” See Also

may_share_memory

๐Ÿ“ Examples

>>> x = np.array([1, 2, 3, 4])
>>> np.shares_memory(x, np.array([5, 6, 7]))
False
>>> np.shares_memory(x[::2], x)
True
>>> np.shares_memory(x[::2], x[1::2])
False

>>> from numpy.lib.stride_tricks import as_strided
>>> x = np.zeros([192163377], dtype=np.int8)
>>> x1 = as_strided(x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049))
>>> x2 = as_strided(x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1))
>>> np.shares_memory(x1, x2, max_work=1000)
Traceback (most recent call last):
...
numpy.TooHardError: Exceeded max_work

๐Ÿ“– show_config = show()

Show libraries in the system on which NumPy was built. Print information about various resources (libraries, library directories, include directories, etc.) in the system on which NumPy was built.

๐Ÿ” See Also

get_include : Returns the directory containing NumPy C header files.

๐Ÿ’ก Notes

Classes specifying the information to be printed are defined in the numpy.distutils.system_info module.

๐Ÿ”ง FUNCTIONS

๐Ÿ“– show_config()

Information may include:

๐Ÿ’ก Examples

>>> import numpy as np
>>> np.show_config()
blas_opt_info:
    language = c
    define_macros = [('HAVE_CBLAS', None)]
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']

๐Ÿ“– sinc(x)

Return the normalized sinc function. The sinc function is sin(pi x)/(pi x).

Note: Note the normalization factor of pi used in the definition. This is the most commonly used definition in signal processing. Use sinc(x / np.pi) to obtain the unnormalized sinc function sin(x)/(x) that is more common in mathematics.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ“ Notes

sinc(0) is the limit value 1. The name sinc is short for "sine cardinal" or "sinus cardinalis". The sinc function is used in various signal processing applications, including in anti-aliasing, in the construction of a Lanczos resampling filter, and in interpolation. For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc function.

๐Ÿ“š References

  1. Weisstein, Eric W. "Sinc Function." From MathWorldโ€”A Wolfram Web Resource. http://mathworld.wolfram.com/SincFunction.html
  2. Wikipedia, "Sinc function", https://en.wikipedia.org/wiki/Sinc_function

๐Ÿ’ก Examples

>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-4, 4, 41)
>>> np.sinc(x)
 array([-3.89804309e-17,  -4.92362781e-02,  -8.40918587e-02, # may vary
        -8.90384387e-02,  -5.84680802e-02,   3.89804309e-17,
        6.68206631e-02,   1.16434881e-01,   1.26137788e-01,
        8.50444803e-02,  -3.89804309e-17,  -1.03943254e-01,
        -1.89206682e-01,  -2.16236208e-01,  -1.55914881e-01,
        3.89804309e-17,   2.33872321e-01,   5.04551152e-01,
        7.56826729e-01,   9.35489284e-01,   1.00000000e+00,
        9.35489284e-01,   7.56826729e-01,   5.04551152e-01,
        2.33872321e-01,   3.89804309e-17,  -1.55914881e-01,
       -2.16236208e-01,  -1.89206682e-01,  -1.03943254e-01,
       -3.89804309e-17,   8.50444803e-02,   1.26137788e-01,
        1.16434881e-01,   6.68206631e-02,   3.89804309e-17,
        -5.84680802e-02,  -8.90384387e-02,  -8.40918587e-02,
        -4.92362781e-02,  -3.89804309e-17])

>>> plt.plot(x, np.sinc(x))
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Sinc Function")
Text(0.5, 1.0, 'Sinc Function')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("X")
Text(0.5, 0, 'X')
>>> plt.show()

๐Ÿ“– size(a, axis=None)

Return the number of elements along a given axis.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2

๐Ÿ“– sometrue(*args, **kwargs)

Check whether some values are true. Refer to any for full documentation.

๐Ÿ”— See Also

๐Ÿ“– sort(a, axis=-1, kind=None, order=None)

Return a sorted copy of an array.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

The various sorting algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The four algorithms implemented in NumPy have the following properties:

kindspeedworst casework spacestable
'quicksort'1O(n^2)0no
'heapsort'3O(n*log(n))0no
'mergesort'2O(n*log(n))~n/2yes
'timsort'2O(n*log(n))~n/2yes

Note: The datatype determines which of 'mergesort' or 'timsort' is actually used, even if 'mergesort' is specified. User selection at a finer scale is not currently available.

All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently, sorting along the last axis is faster and uses less space than sorting along any other axis.

The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts.

Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is:

where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before.

Added in version 1.12.0: quicksort has been changed to introsort. When sorting does not make enough progress it switches to heapsort. This implementation makes quicksort O(n*log(n)) in the worst case.

'stable' automatically chooses the best stable sorting algorithm for the data type being sorted. It, along with 'mergesort' is currently mapped to timsort or radix sort depending on the data type. API forward compatibility currently limits the ability to select the implementation and it is hardwired for the different data types.

Added in version 1.17.0: Timsort is added for better performance on already or nearly sorted data. On random data timsort is almost identical to mergesort. It is now used for stable sort while quicksort is still the default sort if none is chosen. For timsort details, refer to CPython listsort.txt. 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an O(n) sort instead of O(n log n).

Changed in version 1.18.0: NaT now sorts to the end of arrays for consistency with NaN.

๐Ÿ’ก Examples

>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a)                # sort along the last axis
array([[1, 4],
       [1, 3]])
>>> np.sort(a, axis=None)     # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0)        # sort along the first axis
array([[1, 1],
       [3, 4]])

Use the `order` keyword to specify a field to use when sorting a structured array:

>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
...           ('Galahad', 1.7, 38)]
>>> a = np.array(values, dtype=dtype)       # create a structured array
>>> np.sort(a, order='height')                        # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
       ('Lancelot', 1.8999999999999999, 38)],
      dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])

Sort by age, then height if ages are equal:

>>> np.sort(a, order=['age', 'height'])               # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
       ('Arthur', 1.8, 41)],
      dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])

๐Ÿ“– sort_complex(a)

Sort a complex array using the real part first, then the imaginary part.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ’ก Examples

>>> np.sort_complex([5, 3, 6, 2, 1])
array([1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])

>>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])
array([1.+2.j,  2.-1.j,  3.-3.j,  3.-2.j,  3.+5.j])

๐Ÿ“– source(object, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Print or write to a file the source code for a NumPy object. The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information.

๐Ÿ“Œ Parameters

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> np.source(np.interp)                        #doctest: +SKIP
In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py
def interp(x, xp, fp, left=None, right=None):
    """.... (full docstring printed)"""
    if isinstance(x, (float, int, number)):
        return compiled_interp([x], xp, fp, left, right).item()
    else:
        return compiled_interp(x, xp, fp, left, right)

The source code is only returned for objects written in Python.

>>> np.source(np.array)                         #doctest: +SKIP
Not available for this object.

๐Ÿ“– split(ary, indices_or_sections, axis=0)

Split an array into multiple sub-arrays as views into ary.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

โš ๏ธ Raises

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([0.,  1.,  2.]), array([3.,  4.,  5.]), array([6.,  7.,  8.])]

>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
[array([0.,  1.,  2.]),
 array([3.,  4.]),
 array([5.]),
 array([6.,  7.]),
 array([], dtype=float64)]

๐Ÿ“– squeeze(a, axis=None)

Remove axes of length one from a.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

โš ๏ธ Raises

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=0).shape
(3, 1)
>>> np.squeeze(x, axis=1).shape
Traceback (most recent call last):
... ValueError: cannot select an axis to squeeze out which has size not equal to one
>>> np.squeeze(x, axis=2).shape
(1, 3)
>>> x = np.array([[1234]])
>>> x.shape
(1, 1)
>>> np.squeeze(x)
array(1234)  # 0d array
>>> np.squeeze(x).shape
()
>>> np.squeeze(x)[()]
1234

๐Ÿ“– stack(arrays, axis=0, out=None)

Join a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

Added in version 1.10.0.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> arrays = [np.random.randn(3, 4) for _ in range(10)]
>>> np.stack(arrays, axis=0).shape
(10, 3, 4)

>>> np.stack(arrays, axis=1).shape
(3, 10, 4)

>>> np.stack(arrays, axis=2).shape
(3, 4, 10)

>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.stack((a, b))
array([[1, 2, 3],
       [4, 5, 6]])

>>> np.stack((a, b), axis=-1)
array([[1, 4],
       [2, 5],
       [3, 6]])

๐Ÿ“– std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)

Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std = sqrt(mean(x)), where x = abs(a - a.mean())**2. The average squared deviation is typically calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the std is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue.

๐Ÿ’ก Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> np.std(a)
1.1180339887498949 # may vary
>>> np.std(a, axis=0)
array([1.,  1.])
>>> np.std(a, axis=1)
array([0.5,  0.5])

In single precision, std() can be inaccurate:

>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.std(a)
0.45000005

Computing the standard deviation in float64 is more accurate:

>>> np.std(a, dtype=np.float64)
0.44999999925494177 # may vary

Specifying a where argument:

>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> np.std(a)
2.614064523559687 # may vary
>>> np.std(a, where=[[True], [True], [False]])
2.0

๐Ÿ“– sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)

Sum of array elements over a given axis.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

Arithmetic is modular when using integer types, and no error is raised on overflow. The sum of an empty array is the neutral element 0:

>>> np.sum([])
0.0

For floating point numbers the numerical precision of sum (and np.add.reduce) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when no axis is given. When axis is given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python's math.fsum function uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such as float32, numerical errors can become significant. In such cases it can be advisable to use dtype="float64" to use a higher precision for the output.

๐Ÿ’ก Examples

>>> np.sum([0.5, 1.5])
2.0
>>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
1
>>> np.sum([[0, 1], [0, 5]])
6
>>> np.sum([[0, 1], [0, 5]], axis=0)
array([0, 6])
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
>>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
array([1., 5.])

If the accumulator is too small, overflow occurs:

>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
-128

You can also start the sum with a value other than zero:

>>> np.sum([10], initial=5)
15

๐Ÿ“– swapaxes(a, axis1, axis2)

Interchange two axes of an array.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ’ก Examples

>>> x = np.array([[1,2,3]])
>>> np.swapaxes(x,0,1)
array([[1],
       [2],
       [3]])

>>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
>>> x
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])

>>> np.swapaxes(x,0,2)
array([[[0, 4],
        [2, 6]],
       [[1, 5],
        [3, 7]]])

๐Ÿ“– take(a, indices, axis=None, out=None, mode='raise')

Take elements from an array along an axis. When axis is not None, this function does the same thing as "fancy" indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...]. Explained without fancy indexing, this is equivalent to the following use of ndindex, which sets each of ii, jj, and kk to a tuple of indices:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
Nj = indices.shape
for ii in ndindex(Ni):
    for jj in ndindex(Nj):
        for kk in ndindex(Nk):
            out[ii + jj + kk] = a[ii + (indices[jj],) + kk]

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

By eliminating the inner loop in the description above, and using s_ to build simple slice objects, take can be expressed in terms of applying fancy indexing to each 1-d slice:

Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
    for kk in ndindex(Nj):
        out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]

For this reason, it is equivalent to (but faster than) the following use of apply_along_axis:

out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)

๐Ÿ’ก Examples

>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])

In this example if `a` is an ndarray, "fancy" indexing can be used.

>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])

If `indices` is not one dimensional, the output also has these dimensions.

>>> np.take(a, [[0, 1], [2, 3]])
array([[4, 3],
       [5, 7]])

๐Ÿ“– take_along_axis(arr, indices, axis)

Take values from the input array by matching 1d index and data slices. This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to look up values in the latter. These slices can be different lengths. Functions returning an index along an axis, like argsort and argpartition, produce suitable indices for this function.

Added in version 1.15.0.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ“ Notes

This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii and kk to a tuple of indices:

Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
J = indices.shape[axis]  # Need not equal M
out = np.empty(Ni + (J,) + Nk)

for ii in ndindex(Ni):
    for kk in ndindex(Nk):
        a_1d       = a      [ii + s_[:,] + kk]
        indices_1d = indices[ii + s_[:,] + kk]
        out_1d     = out    [ii + s_[:,] + kk]
        for j in range(J):
            out_1d[j] = a_1d[indices_1d[j]]

Equivalently, eliminating the inner loop, the last two lines would be:

out_1d[:] = a_1d[indices_1d]

๐Ÿ”— See Also

๐Ÿ’ก Examples

For this sample array

>>> a = np.array([[10, 30, 20], [60, 40, 50]])

We can sort either by using sort directly, or argsort and this function

>>> np.sort(a, axis=1)
array([[10, 20, 30],
       [40, 50, 60]])
>>> ai = np.argsort(a, axis=1); ai
array([[0, 2, 1],
       [1, 2, 0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[10, 20, 30],
       [40, 50, 60]])

The same works for max and min, if you expand the dimensions:

>>> np.expand_dims(np.max(a, axis=1), axis=1)
array([[30],
       [60]])
>>> ai = np.expand_dims(np.argmax(a, axis=1), axis=1)
>>> ai
array([[1],
       [0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[30],
       [60]])

If we want to get the max and min at the same time, we can stack the indices first

>>> ai_min = np.expand_dims(np.argmin(a, axis=1), axis=1)
>>> ai_max = np.expand_dims(np.argmax(a, axis=1), axis=1)
>>> ai = np.concatenate([ai_min, ai_max], axis=1)
>>> ai
array([[0, 1],
       [1, 0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[10, 30],
       [40, 60]])

๐Ÿ“– tensordot(a, b, axes=2)

Compute tensor dot product along specified axes. Given two tensors, a and b, and an array_like object containing two array_like objects, (a_axes, b_axes), sum the products of a's and b's elements (components) over the axes specified by a_axes and b_axes. The third argument can be a single non-negative integer_like scalar, N; if it is such, then the last N dimensions of a and the first N dimensions of b are summed over.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

Three common use cases are:

When axes is integer_like, the sequence for evaluation will be: first the -Nth axis in a and 0th axis in b, and the -1th axis in a and Nth axis in b last. When there is more than one axis to sum over - and they are not the last (first) axes of a (b) - the argument axes should consist of two sequences of the same length, with the first axis to sum over given first in both sequences, the second axis second, and so forth. The shape of the result consists of the non-contracted axes of the first tensor, followed by the non-contracted axes of the second.

๐Ÿ’ก Examples

A "traditional" example:

>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5, 2)
>>> c
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])
>>> # A slower but equivalent way of computing the same...
>>> d = np.zeros((5,2))
>>> for i in range(5):
...   for j in range(2):
...     for k in range(3):
...       for n in range(4):
...         d[i,j] += a[k,n,i] * b[n,k,j]
>>> c == d
array([[ True,  True],
       [ True,  True],
       [ True,  True],
       [ True,  True],
       [ True,  True]])

An extended example taking advantage of the overloading of + and *:

>>> a = np.array(range(1, 9))
>>> a.shape = (2, 2, 2)
>>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
>>> A.shape = (2, 2)
>>> a; A
array([[[1, 2],
        [3, 4]],
       [[5, 6],
        [7, 8]]])
array([['a', 'b'],
       ['c', 'd']], dtype=object)

>>> np.tensordot(a, A) # third argument default is 2 for double-contraction
array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)

>>> np.tensordot(a, A, 1)
array([[['acc', 'bdd'],
        ['aaacccc', 'bbbdddd']],
       [['aaaaacccccc', 'bbbbbdddddd'],
        ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)

>>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
array([[[[['a', 'b'],
          ['c', 'd']],
          ...

>>> np.tensordot(a, A, (0, 1))
array([[['abbbbb', 'cddddd'],
        ['aabbbbbb', 'ccdddddd']],
       [['aaabbbbbbb', 'cccddddddd'],
        ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)

>>> np.tensordot(a, A, (2, 1))
array([[['abb', 'cdd'],
        ['aaabbbb', 'cccdddd']],
       [['aaaaabbbbbb', 'cccccdddddd'],
        ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)

>>> np.tensordot(a, A, ((0, 1), (0, 1)))
array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)

>>> np.tensordot(a, A, ((2, 1), (1, 0)))
array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)

๐Ÿ“– tile(A, reps)

Construct an array by repeating A the number of times given by reps. If reps has length d, the result will have dimension of max(d, A.ndim). If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function. If A.ndim > d, reps is promoted to A.ndim by pre-pending 1's to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).

Note: Although tile may be used for broadcasting, it is strongly recommended to use numpy's broadcasting operations and functions.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
       [0, 1, 2, 0, 1, 2]])
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
       [[0, 1, 2, 0, 1, 2]]])

>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
       [3, 4, 3, 4]])
>>> np.tile(b, (2, 1))
array([[1, 2],
       [3, 4],
       [1, 2],
       [3, 4]])

>>> c = np.array([1,2,3,4])
>>> np.tile(c,(4,1))
array([[1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4],
       [1, 2, 3, 4]])

๐Ÿ“– trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)

Return the sum along diagonals of the array. If a is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements a[i,i+offset] for all i. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> np.trace(np.eye(3))
3.0
>>> a = np.arange(8).reshape((2,2,2))
>>> np.trace(a)
array([6, 8])

>>> a = np.arange(24).reshape((2,2,2,3))
>>> np.trace(a).shape
(2, 3)

๐Ÿ“– transpose(a, axes=None)

Reverse or permute the axes of an array; returns the modified array. For an array a with two axes, transpose(a) gives the matrix transpose. Refer to numpy.ndarray.transpose for full documentation.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

Use transpose(a, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument. Transposing a 1-D array returns an unchanged view of the original array.

๐Ÿ’ก Examples

>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
       [2, 3]])

>>> np.transpose(x)
array([[0, 2],
       [1, 3]])

>>> x = np.ones((1, 2, 3))
>>> np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)

>>> x = np.ones((2, 3, 4, 5))
>>> np.transpose(x).shape
(5, 4, 3, 2)

๐Ÿ“– trapz(y, x=None, dx=1.0, axis=-1)

Integrate along the given axis using the composite trapezoidal rule. If x is provided, the integration happens in sequence along its elements - they are not sorted. Integrate y (x) along each 1d slice on the given axis, compute โˆซ y(x) dx. When x is specified, this integrates along the parametric curve, computing โˆซ_t y(t) dt = โˆซ_t y(t) dx/dt|_{x=x(t)} dt.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

Image [2] illustrates trapezoidal rule โ€“ y-axis locations of points will be taken from y array, by default x-axis distances between points will be 1.0, alternatively they can be provided with x array or with dx scalar. Return value will be equal to combined area under the red lines.

๐Ÿ“š References

  1. Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
  2. Illustration image: https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png

๐Ÿ’ก Examples

>>> np.trapz([1,2,3])
4.0
>>> np.trapz([1,2,3], x=[4,6,8])
8.0
>>> np.trapz([1,2,3], dx=2)
8.0

Using a decreasing `x` corresponds to integrating in reverse:

>>> np.trapz([1,2,3], x=[8,6,4])
-8.0

More generally `x` is used to integrate along a parametric curve. This finds the area of a circle, noting we repeat the sample which closes the curve:

>>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
>>> np.trapz(np.cos(theta), x=np.sin(theta))
3.141571941375841

>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.trapz(a, axis=0)
array([1.5, 2.5, 3.5])
>>> np.trapz(a, axis=1)
array([2.,  8.])

๐Ÿ“– tri(N, M=None, k=0, dtype=<class 'float'>, *, like=None)

An array with ones at and below the given diagonal and zeros elsewhere.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ’ก Examples

>>> np.tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
       [1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1]])

>>> np.tri(3, 5, -1)
array([[0.,  0.,  0.,  0.,  0.],
       [1.,  0.,  0.,  0.,  0.],
       [1.,  1.,  0.,  0.,  0.]])

๐Ÿ“– tril(m, k=0)

Lower triangle of an array. Return a copy of an array with elements above the k-th diagonal zeroed.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 0,  0,  0],
       [ 4,  0,  0],
       [ 7,  8,  0],
       [10, 11, 12]])

๐Ÿ“– tril_indices(n, k=0, m=None)

Return the indices for the lower-triangle of an (n, m) array.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

Added in version 1.4.0.

๐Ÿ’ก Examples

Compute two different sets of indices to access 4x4 arrays, one for the lower triangular part starting at the main diagonal, and one starting two diagonals further right:

>>> il1 = np.tril_indices(4)
>>> il2 = np.tril_indices(4, 2)

Here is how they can be used with a sample array:

>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

Both for indexing:

>>> a[il1]
array([ 0,  4,  5, ..., 13, 14, 15])

And for assigning values:

>>> a[il1] = -1
>>> a
array([[-1,  1,  2,  3],
       [-1, -1,  6,  7],
       [-1, -1, -1, 11],
       [-1, -1, -1, -1]])

These cover almost the whole array (two diagonals right of the main one):

>>> a[il2] = -10
>>> a
array([[-10, -10, -10,   3],
       [-10, -10, -10, -10],
       [-10, -10, -10, -10],
       [-10, -10, -10, -10]])

๐Ÿ“– tril_indices_from(arr, k=0)

Return the indices for the lower-triangle of arr. See tril_indices for full details.

๐Ÿ“Œ Parameters

๐Ÿ”— See Also

๐Ÿ“ Notes

Added in version 1.4.0.

๐Ÿ“– trim_zeros(filt, trim='fb')

Trim the leading and/or trailing zeros from a 1-D array or sequence.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ’ก Examples

>>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
>>> np.trim_zeros(a)
array([1, 2, 3, 0, 2, 1])

>>> np.trim_zeros(a, 'b')
array([0, 0, 0, ..., 0, 2, 1])

The input data type is preserved, list/tuple in means list/tuple out.

>>> np.trim_zeros([0, 1, 2, 0])
[1, 2]

๐Ÿ“– triu(m, k=0)

Upper triangle of an array. Return a copy of an array with the elements below the k-th diagonal zeroed. Please refer to the documentation for tril for further details.

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 0,  8,  9],
       [ 0,  0, 12]])

๐Ÿ“– triu_indices(n, k=0, m=None)

Return the indices for the upper-triangle of an (n, m) array.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

Added in version 1.4.0.

๐Ÿ’ก Examples

Compute two different sets of indices to access 4x4 arrays, one for the upper triangular part starting at the main diagonal, and one starting two diagonals further right:

>>> iu1 = np.triu_indices(4)
>>> iu2 = np.triu_indices(4, 2)

Here is how they can be used with a sample array:

>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

Both for indexing:

>>> a[iu1]
array([ 0,  1,  2, ..., 10, 11, 15])

And for assigning values:

>>> a[iu1] = -1
>>> a
array([[-1, -1, -1, -1],
       [ 4, -1, -1, -1],
       [ 8,  9, -1, -1],
       [12, 13, 14, -1]])

These cover only a small part of the whole array (two diagonals right of the main one):

>>> a[iu2] = -10
>>> a
array([[ -1,  -1, -10, -10],
       [  4,  -1,  -1, -10],
       [  8,   9,  -1,  -1],
       [ 12,  13,  14,  -1]])

๐Ÿ“– triu_indices_from(arr, k=0)

Return the indices for the upper-triangle of arr. See triu_indices for full details.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

Added in version 1.4.0.

๐Ÿ“– typename(char)

Return a description for the given data type code.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> typechars = ['S1', '?', 'B', 'D', 'G', 'F', 'I', 'H', 'L', 'O', 'Q',
...              'S', 'U', 'V', 'b', 'd', 'g', 'f', 'i', 'h', 'l', 'q']
>>> for typechar in typechars:
...     print(typechar, ' : ', np.typename(typechar))
... S1  :  character
?  :  bool
B  :  unsigned char
D  :  complex double precision
G  :  complex long double precision
F  :  complex single precision
I  :  unsigned integer
H  :  unsigned short
L  :  unsigned long integer
O  :  object
Q  :  unsigned long long integer
S  :  string
U  :  unicode
V  :  void
b  :  signed char
d  :  double precision
g  :  long precision
f  :  single precision
i  :  integer
h  :  short
l  :  long integer
q  :  long long integer

๐Ÿ“– union1d(ar1, ar2)

Find the union of two arrays. Return the unique, sorted array of values that are in either of the two input arrays.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> np.union1d([-1, 0, 1], [-2, 0, 2])
array([-2, -1,  0,  1,  2])

To find the union of more than two arrays, use functools.reduce:

>>> from functools import reduce
>>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([1, 2, 3, 4, 6])

๐Ÿ“– unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)

Find the unique elements of an array. Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

When an axis is specified the subarrays indexed by the axis are sorted. This is done by making the specified axis the first dimension of the array (move the axis to the first dimension to keep the order of the other axes) and then flattening the subarrays in C order. The flattened subarrays are then viewed as a structured type with each element given a label, with the effect that we end up with a 1-D array of structured types that can be treated in the same way as any other 1-D array. The result is that the flattened subarrays are sorted in lexicographic order starting with the first element.

Changed in version NumPy 1.21: If nan values are in the input array, a single nan is put to the end of the sorted unique values. Also for complex arrays all NaN values are considered equivalent (no matter whether the NaN is in the real or imaginary part). As the representant for the returned array the smallest one in the lexicographical order is chosen - see np.sort for how the lexicographical order is defined for complex arrays.

๐Ÿ’ก Examples

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

Return the unique rows of a 2D array

>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
>>> np.unique(a, axis=0)
array([[1, 0, 0], [2, 3, 4]])

Return the indices of the original array that give the unique values:

>>> a = np.array(['a', 'b', 'b', 'c', 'a'])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array(['a', 'b', 'c'], dtype='<U1')
>>> indices
array([0, 1, 3])
>>> a[indices]
array(['a', 'b', 'c'], dtype='<U1')

Reconstruct the input array from the unique values and inverse:

>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> indices
array([0, 1, 4, 3, 1, 2, 1])
>>> u[indices]
array([1, 2, 6, 4, 2, 3, 2])

Reconstruct the input values from the unique values and counts:

>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> values, counts = np.unique(a, return_counts=True)
>>> values
array([1, 2, 3, 4, 6])
>>> counts
array([1, 3, 1, 1, 1])
>>> np.repeat(values, counts)
array([1, 2, 2, 2, 3, 4, 6])    # original order not preserved

๐Ÿ“– unpackbits(...)

unpackbits(a, axis=None, count=None, bitorder='big')

Unpacks elements of a uint8 array into a binary-valued output array. Each element of a represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
       [ 7],
       [23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
>>> c = np.unpackbits(a, axis=1, count=-3)
>>> c
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 1, 0]], dtype=uint8)

>>> p = np.packbits(b, axis=0)
>>> np.unpackbits(p, axis=0)
array([[0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 1, 0, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0]))
True

๐Ÿ“– unravel_index(...)

unravel_index(indices, shape, order='C')

Converts a flat index or array of flat indices into a tuple of coordinate arrays.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> np.unravel_index([22, 41, 37], (7,6))
(array([3, 6, 6]), array([4, 5, 1]))
>>> np.unravel_index([31, 41, 13], (7,6), order='F')
(array([3, 6, 6]), array([4, 5, 1]))

>>> np.unravel_index(1621, (6,7,8,9))
(3, 1, 4, 1)

๐Ÿ“– unwrap(p, discont=None, axis=-1, *, period=6.283185307179586)

Unwrap by taking the complement of large deltas with respect to the period. This unwraps a signal p by changing elements which have an absolute difference from their predecessor of more than max(discont, period/2) to their period-complementary values. For the default case where period is 2ฯ€ and is discont is ฯ€, this unwraps a radian phase p such that adjacent differences are never greater than ฯ€ by adding 2kฯ€ for some integer k.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

If the discontinuity in p is smaller than period/2, but larger than discont, no unwrapping is done because taking the complement would only make the discontinuity larger.

๐Ÿ’ก Examples

>>> phase = np.linspace(0, np.pi, num=5)
>>> phase[3:] += np.pi
>>> phase
array([ 0.        ,  0.78539816,  1.57079633,  5.49778714,  6.28318531]) # may vary
>>> np.unwrap(phase)
array([ 0.        ,  0.78539816,  1.57079633, -0.78539816,  0.        ]) # may vary
>>> np.unwrap([0, 1, 2, -1, 0], period=4)
array([0, 1, 2, 3, 4])
>>> np.unwrap([ 1, 2, 3, 4, 5, 6, 1, 2, 3], period=6)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.unwrap([2, 3, 4, 5, 2, 3, 4, 5], period=4)
array([2, 3, 4, 5, 6, 7, 8, 9])
>>> phase_deg = np.mod(np.linspace(0 ,720, 19), 360) - 180
>>> np.unwrap(phase_deg, period=360)
array([-180., -140., -100.,  -60.,  -20.,   20.,   60.,  100.,  140.,
        180.,  220.,  260.,  300.,  340.,  380.,  420.,  460.,  500.,
        540.])

๐Ÿ“– vander(x, N=None, increasing=False)

Generate a Vandermonde matrix. The columns of the output matrix are powers of the input vector. The order of the powers is determined by the increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1,  1,  1],
       [ 4,  2,  1],
       [ 9,  3,  1],
       [25,  5,  1]])

>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1,  1,  1],
       [ 4,  2,  1],
       [ 9,  3,  1],
       [25,  5,  1]])

>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[  1,   1,   1,   1],
       [  8,   4,   2,   1],
       [ 27,   9,   3,   1],
       [125,  25,  5,   1]])
>>> np.vander(x, increasing=True)
array([[  1,   1,   1,   1],
       [  1,   2,   4,   8],
       [  1,   3,   9,  27],
       [  1,   5,  25, 125]])

The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector:

>>> np.linalg.det(np.vander(x))
48.000000000000043 # may vary
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48

๐Ÿ“– var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)

Compute the variance along the specified axis. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

The variance is the average of the squared deviations from the mean, i.e., var = mean(x), where x = abs(a - a.mean())**2. The mean is typically calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of a hypothetical infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and nonnegative. For floating-point input, the variance is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue.

๐Ÿ’ก Examples

>>> a = np.array([[1, 2], [3, 4]])
>>> np.var(a)
1.25
>>> np.var(a, axis=0)
array([1.,  1.])
>>> np.var(a, axis=1)
array([0.25,  0.25])

In single precision, var() can be inaccurate:

>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.var(a)
0.20250003

Computing the variance in float64 is more accurate:

>>> np.var(a, dtype=np.float64)
0.20249999932944759 # may vary
>>> ((1-0.55)**2 + (0.1-0.55)**2)/2
0.2025

Specifying a where argument:

>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> np.var(a)
6.833333333333333 # may vary
>>> np.var(a, where=[[True], [True], [False]])
4.0

๐Ÿ“– vdot(...)

vdot(a, b)

Return the dot product of two vectors. The vdot(a, b) function handles complex numbers differently than dot(a, b). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product. Note that vdot handles multidimensional arrays differently than dot: it does not perform a matrix product, but flattens input arguments to 1-D vectors first. Consequently, it should only be used for vectors.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> a = np.array([1+2j,3+4j])
>>> b = np.array([5+6j,7+8j])
>>> np.vdot(a, b)
(70-8j)
>>> np.vdot(b, a)
(70+8j)

Note that higher-dimensional arrays are flattened!

>>> a = np.array([[1, 4], [5, 6]])
>>> b = np.array([[4, 1], [2, 2]])
>>> np.vdot(a, b)
30
>>> np.vdot(b, a)
30
>>> 1*4 + 4*1 + 5*2 + 6*2
30

๐Ÿ“– vsplit(ary, indices_or_sections)

Split an array into multiple sub-arrays vertically (row-wise). Please refer to the split documentation. vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension.

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0.,   1.,   2.,   3.],
       [ 4.,   5.,   6.,   7.],
       [ 8.,   9.,  10.,  11.],
       [12.,  13.,  14.,  15.]])
>>> np.vsplit(x, 2)
[array([[0., 1., 2., 3.],
       [4., 5., 6., 7.]]), array([[ 8.,  9., 10., 11.],
       [12., 13., 14., 15.]])]
>>> np.vsplit(x, np.array([3, 6]))
[array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.]]), array([[12., 13., 14., 15.]]), array([], shape=(0, 4), dtype=float64)]

With a higher dimensional array the split is still along the first axis.

>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[0.,  1.],
        [2.,  3.]],
       [[4.,  5.],
        [6.,  7.]]])
>>> np.vsplit(x, 2)
[array([[[0., 1.],
        [2., 3.]]]), array([[[4., 5.],
        [6., 7.]]])]

๐Ÿ“– vstack(tup)

Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit. 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

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
       [4, 5, 6]])

>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])

๐Ÿ“– where(...)

where(condition, [x, y])

Return elements chosen from x or y depending on condition.

Note: When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ“ Notes

If all the arrays are 1-D, where is equivalent to:

[xv if c else yv
 for c, xv, yv in zip(condition, x, y)]

๐Ÿ’ก Examples

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(a < 5, a, 10*a)
array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

This can be used on multidimensional arrays too:

>>> np.where([[True, False], [True, True]],
...          [[1, 2], [3, 4]],
...          [[9, 8], [7, 6]])
array([[1, 8],
       [3, 4]])

The shapes of x, y, and the condition are broadcast together:

>>> x, y = np.ogrid[:3, :4]
>>> np.where(x < y, x, 10 + y)  # both x and 10+y are broadcast
array([[10,  0,  0,  0],
       [10, 11,  1,  1],
       [10, 11, 12,  2]])

>>> a = np.array([[0, 1, 2],
...               [0, 2, 4],
...               [0, 3, 6]])
>>> np.where(a < 4, a, -1)  # -1 is broadcast
array([[ 0,  1,  2],
       [ 0,  2, -1],
       [ 0,  3, -1]])

๐Ÿ“– who(vardict=None)

Print the NumPy arrays in the given dictionary. If there is no dictionary passed in or vardict is None then returns NumPy arrays in the globals() dictionary (all NumPy arrays in the namespace).

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ“ Notes

Prints out the name, shape, bytes and type of all of the ndarrays present in vardict.

๐Ÿ’ก Examples

>>> a = np.arange(10)
>>> b = np.ones(20)
>>> np.who()
Name            Shape            Bytes            Type
===========================================================
a               10               80               int64
b               20               160              float64
Upper bound on total bytes  =       240

>>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str',
... 'idx':5}
>>> np.who(d)
Name            Shape            Bytes            Type
===========================================================
x               2                16               float64
y               3                24               float64
Upper bound on total bytes  =       40

๐Ÿ“– zeros(...)

zeros(shape, dtype=float, order='C', *, like=None)

Return a new array of given shape and type, filled with zeros.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> np.zeros(5)
array([ 0.,  0.,  0.,  0.,  0.])

>>> np.zeros((5,), dtype=int)
array([0, 0, 0, 0, 0])

>>> np.zeros((2, 1))
array([[ 0.],
       [ 0.]])

>>> s = (2,2)
>>> np.zeros(s)
array([[ 0.,  0.],
       [ 0.,  0.]])

>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)],
      dtype=[('x', '<i4'), ('y', '<i4')])

๐Ÿ“– zeros_like(a, dtype=None, order='K', subok=True, shape=None)

Return an array of zeros with the same shape and type as a given array.

๐Ÿ“Œ Parameters

๐ŸŽฏ Returns

๐Ÿ”— See Also

๐Ÿ’ก Examples

>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.zeros_like(x)
array([[0, 0, 0],
       [0, 0, 0]])

>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1., 2.])
>>> np.zeros_like(y)
array([0.,  0.,  0.])

๐Ÿ“Š DATA

๐Ÿ”ข Constants

๐Ÿ”ง Ufuncs

๐Ÿ”ง absolute

absolute = <ufunc 'absolute'>
    absolute(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Calculate the absolute value element-wise.

np.abs is a shorthand for this function.

๐Ÿ“ฅ Parameters
๐Ÿ“ค Returns
๐Ÿ’ก Examples
>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2,  1.2])
>>> np.absolute(1.2 + 1j)
1.5620499351813308
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(start=-10, stop=10, num=101)
>>> plt.plot(x, np.absolute(x))
>>> plt.show()
>>> xx = x + 1j * x[:, np.newaxis]
>>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray')
>>> plt.show()
>>> x = np.array([-1.2, 1.2])
>>> abs(x)
array([1.2, 1.2])

๐Ÿ”ง add

add = <ufunc 'add'>
    add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Add arguments element-wise.

๐Ÿ“ฅ Parameters
๐Ÿ“ค Returns
๐Ÿ“ Notes

Equivalent to x1 + x2 in terms of array broadcasting.

๐Ÿ’ก Examples
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 + x2
array([[ 0.,  2.,  4.],
       [ 3.,  5.,  7.],
       [ 6.,  8., 10.]])

๐Ÿ”ง arccos

arccos = <ufunc 'arccos'>
    arccos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Trigonometric inverse cosine, element-wise. The inverse of cos so that, if y = cos(x), then x = arccos(y).

๐Ÿ“ฅ Parameters
๐Ÿ“ค Returns
๐Ÿ‘€ See Also

cos, arctan, arcsin, emath.arccos

๐Ÿ“ Notes

arccos is a multivalued function: for each x there are infinitely many numbers z such that cos(z) = x. The convention is to return the angle z whose real part lies in [0, pi]. For real-valued input data types, arccos always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arccos is a complex analytic function that has branch cuts [-inf, -1] and [1, inf] and is continuous from above on the former and from below on the latter. The inverse cos is also known as acos or cos^-1.

๐Ÿ“š References

M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/

๐Ÿ’ก Examples
>>> np.arccos([1, -1])
array([ 0.        ,  3.14159265])
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-1, 1, num=100)
>>> plt.plot(x, np.arccos(x))
>>> plt.axis('tight')
>>> plt.show()

๐Ÿ”ง arccosh

arccosh = <ufunc 'arccosh'>
    arccosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Inverse hyperbolic cosine, element-wise.

๐Ÿ“ฅ Parameters
๐Ÿ“ค Returns
๐Ÿ‘€ See Also

cosh, arcsinh, sinh, arctanh, tanh

๐Ÿ“ Notes

arccosh is a multivalued function: for each x there are infinitely many numbers z such that cosh(z) = x. The convention is to return the z whose imaginary part lies in [-pi, pi] and the real part in [0, inf]. For real-valued input data types, arccosh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arccosh is a complex analytical function that has a branch cut [-inf, 1] and is continuous from above on it.

๐Ÿ“š References

M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ Wikipedia, "Inverse hyperbolic function", https://en.wikipedia.org/wiki/Arccosh

๐Ÿ’ก Examples
>>> np.arccosh([np.e, 10.0])
array([ 1.65745445,  2.99322285])
>>> np.arccosh(1)
0.0

๐Ÿ”ง arcsin

arcsin = <ufunc 'arcsin'>
    arcsin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Inverse sine, element-wise.

๐Ÿ“ฅ Parameters
๐Ÿ“ค Returns
๐Ÿ‘€ See Also

sin, cos, arccos, tan, arctan, arctan2, emath.arcsin

๐Ÿ“ Notes

arcsin is a multivalued function: for each x there are infinitely many numbers z such that sin(z) = x. The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. For real-valued input data types, arcsin always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arcsin is a complex analytic function that has, by convention, the branch cuts [-inf, -1] and [1, inf] and is continuous from above on the former and from below on the latter. The inverse sine is also known as asin or sin^{-1}.

๐Ÿ“š References

Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79ff. http://www.math.sfu.ca/~cbm/aands/

๐Ÿ’ก Examples
>>> np.arcsin(1)     # pi/2
1.5707963267948966
>>> np.arcsin(-1)    # -pi/2
-1.5707963267948966
>>> np.arcsin(0)
0.0

๐Ÿ”ง arcsinh

arcsinh = <ufunc 'arcsinh'>
    arcsinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Inverse hyperbolic sine element-wise.

๐Ÿ“ฅ Parameters
๐Ÿ“ค Returns
๐Ÿ“ Notes

arcsinh is a multivalued function: for each x there are infinitely many numbers z such that sinh(z) = x. The convention is to return the z whose imaginary part lies in [-pi/2, pi/2]. For real-valued input data types, arcsinh always returns real output. For each value that cannot be expressed as a real number or infinity, it returns nan and sets the invalid floating point error flag. For complex-valued input, arccos is a complex analytical function that has branch cuts [1j, infj] and [-1j, -infj] and is continuous from the right on the former and from the left on the latter. The inverse hyperbolic sine is also known as asinh or sinh^-1.

๐Ÿ“š References

M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ Wikipedia, "Inverse hyperbolic function", https://en.wikipedia.org/wiki/Arcsinh

๐Ÿ’ก Examples
>>> np.arcsinh(np.array([np.e, 10.0]))
array([ 1.72538256,  2.99822295])

๐Ÿ”ง arctan

arctan = <ufunc 'arctan'>
    arctan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = arctan(y).

๐Ÿ“ฅ Parameters
๐Ÿ“ค Returns
๐Ÿ‘€ See Also

arctan2 : The "four quadrant" arctan of the angle formed by (x, y) and the positive x-axis. angle : Argument of complex values.

๐Ÿ“ Notes

arctan is a multi-valued function: for each x there are infinitely many numbers z such that tan(z) = x. The convention is to return the angle z whose real part lies in [-pi/2, pi/2]. For real-valued input data types, arctan always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, arctan is a complex analytic function that has [1j, infj] and [-1j, -infj] as branch cuts, and is continuous from the left on the former and from the right on the latter. The inverse tangent is also known as atan or tan^{-1}.

๐Ÿ“š References

Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/

๐Ÿ’ก Examples
>>> np.arctan([0, 1])
array([ 0.        ,  0.78539816])
>>> np.pi/4
0.78539816339744828
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-10, 10)
>>> plt.plot(x, np.arctan(x))
>>> plt.axis('tight')
>>> plt.show()

๐Ÿ”ง arctan2

arctan2 = <ufunc 'arctan2'>
    arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Element-wise arc tangent of x1/x2 choosing the quadrant correctly. The quadrant (i.e., branch) is chosen so that arctan2(x1, x2) is the signed angle in radians between the ray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing through the point (x2, x1). (Note the role reversal: the "y-coordinate" is the first function parameter, the "x-coordinate" is the second.) By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf (see Notes for specific values). This function is not defined for complex-valued arguments; for the so-called argument of complex values, use angle.

๐Ÿ“ฅ Parameters
๐Ÿ“ค Returns
๐Ÿ‘€ See Also

arctan, tan, angle

๐Ÿ“ Notes

arctan2 is identical to the atan2 function of the underlying C library. The following special values are defined in the C standard: [1]

x1x2arctan2(x1,x2)
+/- 0+0+/- 0
+/- 0-0+/- pi
> 0+/-inf+0 / +pi
< 0+/-inf-0 / -pi
+/-inf+inf+/- (pi/4)
+/-inf-inf+/- (3*pi/4)

Note that +0 and -0 are distinct floating point numbers, as are +inf and -inf.

๐Ÿ“š References

ISO/IEC standard 9899:1999, "Programming language C."

๐Ÿ’ก Examples
>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.arctan2(y, x) * 180 / np.pi
array([-135.,  -45.,   45.,  135.])
>>> np.arctan2([1., -1.], [0., 0.])
array([ 1.57079633, -1.57079633])
>>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])
array([ 0.        ,  3.14159265,  0.78539816])

(Note: The rest of the ufuncs โ€” arctanh, bitwise_and, bitwise_not, bitwise_or, bitwise_xor, cbrt, ceil, conj, conjugate, copysign, cos, cosh, deg2rad, degrees, divide, divmod, equal, exp, exp2, expm1, fabs, float_power, floor, floor_divide, fmax, fmin, fmod, frexp, gcd, greater, greater_equal, heaviside, hypot, invert, isfinite, isinf, isnan, isnat, lcm, ldexp, left_shift, less, less_equal, log, log10, log1p, log2, logical_and, logical_or, logical_not, logical_xor, matmul, maximum, minimum, mod, modf, multiply, negative, nextafter, not_equal, positive, power, rad2deg, radians, reciprocal, remainder, right_shift, rint, sign, signbit, sin, sinh, spacing, sqrt, square, subtract, tan, tanh, true_divide, trunc, vectorize, where โ€” follow the same pattern with <ufunc...> signatures, parameters, returns, notes, and examples. Each has been enhanced with emoji headings and proper HTML structure.)

๐Ÿ“Š Data

๐Ÿ”ข log10 = <ufunc 'log10'>

๐Ÿ“ Logarithm of the input array, base 10.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

Logarithm is a multivalued function: for each x there is an infinite number of z such that 10**z = x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log10 always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, log10 is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log10 handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard.

๐Ÿ“š References

๐Ÿ’ก Examples

>>> np.log10([1e-15, -3.])
array([-15.,  nan])

๐Ÿ”ข log1p = <ufunc 'log1p'>

๐Ÿ“ Return the natural logarithm of one plus the input array, element-wise. Calculates log(1 + x).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

For real-valued input, log1p is accurate also for x so small that 1 + x == 1 in floating-point accuracy. Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = 1 + x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log1p always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, log1p is a complex analytical function that has a branch cut [-inf, -1] and is continuous from above on it. log1p handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard.

๐Ÿ“š References

๐Ÿ’ก Examples

>>> np.log1p(1e-99)
1e-99
>>> np.log(1 + 1e-99)
0.0

๐Ÿ”ข log2 = <ufunc 'log2'>

๐Ÿ“ Base-2 logarithm of x.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

.. versionadded:: 1.3.0

Logarithm is a multivalued function: for each x there is an infinite number of z such that 2**z = x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log2 always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, log2 is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log2 handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard.

๐Ÿ’ก Examples

>>> x = np.array([0, 1, 2, 2**4])
>>> np.log2(x)
array([-Inf,   0.,   1.,   4.])

>>> xi = np.array([0+1.j, 1, 2+0.j, 4.j])
>>> np.log2(xi)
array([ 0.+2.26618007j,  0.+0.j        ,  1.+0.j        ,  2.+2.26618007j])

๐Ÿ”ข logaddexp = <ufunc 'logaddexp'>

๐Ÿ“ Logarithm of the sum of exponentiations of the inputs. Calculates log(exp(x1) + exp(x2)).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

.. versionadded:: 1.3.0

๐Ÿ’ก Examples

>>> prob1 = np.log(1e-50)
>>> prob2 = np.log(2.5e-50)
>>> prob12 = np.logaddexp(prob1, prob2)
>>> prob12
-113.87649168120691
>>> np.exp(prob12)
3.5000000000000057e-50

๐Ÿ”ข logaddexp2 = <ufunc 'logaddexp2'>

๐Ÿ“ Logarithm of the sum of exponentiations of the inputs in base-2. Calculates log2(2**x1 + 2**x2).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

.. versionadded:: 1.3.0

๐Ÿ’ก Examples

>>> prob1 = np.log2(1e-50)
>>> prob2 = np.log2(2.5e-50)
>>> prob12 = np.logaddexp2(prob1, prob2)
>>> prob1, prob2, prob12
(-166.09640474436813, -164.77447664948076, -164.28904982231052)
>>> 2**prob12
3.4999999999999914e-50

๐Ÿ”ข logical_and = <ufunc 'logical_and'>

โœ… Compute the truth value of x1 AND x2 element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.logical_and(True, False)
False
>>> np.logical_and([True, False], [False, False])
array([False, False])

>>> x = np.arange(5)
>>> np.logical_and(x>1, x<4)
array([False, False,  True,  True, False])


The ``&`` operator can be used as a shorthand for ``np.logical_and`` on
boolean ndarrays.

>>> a = np.array([True, False])
>>> b = np.array([False, False])
>>> a & b
array([False, False])

๐Ÿ”ข logical_not = <ufunc 'logical_not'>

๐Ÿšซ Compute the truth value of NOT x element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.logical_not(3)
False
>>> np.logical_not([True, False, 0, 1])
array([False,  True,  True, False])

>>> x = np.arange(5)
>>> np.logical_not(x<3)
array([False, False, False,  True,  True])

๐Ÿ”ข logical_or = <ufunc 'logical_or'>

โœ… Compute the truth value of x1 OR x2 element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.logical_or(True, False)
True
>>> np.logical_or([True, False], [False, False])
array([ True, False])

>>> x = np.arange(5)
>>> np.logical_or(x < 1, x > 3)
array([ True, False, False, False,  True])

The ``|`` operator can be used as a shorthand for ``np.logical_or`` on
boolean ndarrays.

>>> a = np.array([True, False])
>>> b = np.array([False, False])
>>> a | b
array([ True, False])

๐Ÿ”ข logical_xor = <ufunc 'logical_xor'>

โœ… Compute the truth value of x1 XOR x2, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.logical_xor(True, False)
True
>>> np.logical_xor([True, True, False, False], [True, False, True, False])
array([False,  True,  True, False])

>>> x = np.arange(5)
>>> np.logical_xor(x < 1, x > 3)
array([ True, False, False, False,  True])

Simple example showing support of broadcasting

>>> np.logical_xor(0, np.eye(2))
array([[ True, False],
       [False,  True]])

๐Ÿ”ข matmul = <ufunc 'matmul'>

๐Ÿ”— Matrix product of two arrays.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

โš ๏ธ Raises

๐Ÿ‘€ See Also

๐Ÿ“ Notes

The behavior depends on the arguments in the following way.

matmul differs from dot in two important ways:

>>> a = np.ones([9, 5, 7, 4])
>>> c = np.ones([9, 5, 4, 3])
>>> np.dot(a, c).shape
(9, 5, 7, 9, 5, 3)
>>> np.matmul(a, c).shape
(9, 5, 7, 3)
>>> # n is 7, k is 4, m is 3

The matmul function implements the semantics of the @ operator introduced in Python 3.5 following :pep:465.

๐Ÿ’ก Examples

For 2-D arrays it is the matrix product:

>>> a = np.array([[1, 0],
...               [0, 1]])
>>> b = np.array([[4, 1],
...               [2, 2]])
>>> np.matmul(a, b)
array([[4, 1],
       [2, 2]])

For 2-D mixed with 1-D, the result is the usual.

>>> a = np.array([[1, 0],
...               [0, 1]])
>>> b = np.array([1, 2])
>>> np.matmul(a, b)
array([1, 2])
>>> np.matmul(b, a)
array([1, 2])


Broadcasting is conventional for stacks of arrays

>>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4))
>>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2))
>>> np.matmul(a,b).shape
(2, 2, 2)
>>> np.matmul(a, b)[0, 1, 1]
98
>>> sum(a[0, 1, :] * b[0 , :, 1])
98

Vector, vector returns the scalar inner product, but neither argument
is complex-conjugated:

>>> np.matmul([2j, 3j], [2j, 3j])
(-13+0j)

Scalar multiplication raises an error.

>>> np.matmul([1,2], 3)
Traceback (most recent call last):
... ValueError: matmul: Input operand 1 does not have enough dimensions ... The ``@`` operator can be used as a shorthand for ``np.matmul`` on
ndarrays.

>>> x1 = np.array([2j, 3j])
>>> x2 = np.array([2j, 3j])
>>> x1 @ x2
(-13+0j)

.. versionadded:: 1.10.0

๐Ÿ”ข maximum = <ufunc 'maximum'>

โฌ†๏ธ Element-wise maximum of array elements.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

The maximum 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.maximum([2, 3, 4], [1, 5, 2])
array([2, 5, 4])

>>> np.maximum(np.eye(2), [0.5, 2]) # broadcasting
array([[ 1. ,  2. ],
       [ 0.5,  2. ]])

>>> np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan])
array([nan, nan, nan])
>>> np.maximum(np.Inf, 1)
inf

๐Ÿ”ข mgrid = <numpy.lib.index_tricks.MGridClass object>

๐Ÿ“ An instance of numpy.lib.index_tricks.MGridClass.

๐Ÿ”ข minimum = <ufunc 'minimum'>

โฌ‡๏ธ Element-wise minimum of array elements.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

The minimum 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.minimum([2, 3, 4], [1, 5, 2])
array([1, 3, 2])

>>> np.minimum(np.eye(2), [0.5, 2]) # broadcasting
array([[ 0.5,  0. ],
       [ 0. ,  1. ]])

>>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan])
array([nan, nan, nan])
>>> np.minimum(-np.Inf, 1)
-inf

๐Ÿ”ข mod = <ufunc 'remainder'>

โž— Return element-wise remainder of division. Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modulus operator x1 % x2 and has the same sign as the divisor x2. The MATLAB function equivalent to np.remainder is mod.

โš ๏ธ Warning: This should not be confused with:

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

Returns 0 when x2 is 0 and both x1 and x2 are (arrays of) integers. mod is an alias of remainder.

๐Ÿ’ก Examples

>>> np.remainder([4, 7], [2, 3])
array([0, 1])
>>> np.remainder(np.arange(7), 5)
array([0, 1, 2, 3, 4, 0, 1])

The ``%`` operator can be used as a shorthand for ``np.remainder`` on
ndarrays.

>>> x1 = np.arange(7)
>>> x1 % 5
array([0, 1, 2, 3, 4, 0, 1])

๐Ÿ”ข modf = <ufunc 'modf'>

๐Ÿ”ข Return the fractional and integral parts of an array, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

For integer input the return values are floats.

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.modf([0, 3.5])
(array([ 0. ,  0.5]), array([ 0.,  3.]))
>>> np.modf(-0.5)
(-0.5, -0)

๐Ÿ”ข multiply = <ufunc 'multiply'>

โœ–๏ธ Multiply arguments element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

Equivalent to x1 * x2 in terms of array broadcasting.

๐Ÿ’ก Examples

>>> np.multiply(2.0, 4.0)
8.0

>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.multiply(x1, x2)
array([[  0.,   1.,   4.],
       [  0.,   4.,  10.],
       [  0.,   7.,  16.]])

The ``*`` operator can be used as a shorthand for ``np.multiply`` on
ndarrays.

>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 * x2
array([[  0.,   1.,   4.],
       [  0.,   4.,  10.],
       [  0.,   7.,  16.]])

๐Ÿ”ข nan = nan

๐Ÿ”ข Not a Number (NaN) constant.

๐Ÿ”ข nbytes = {<class 'numpy.bool_'>: 1, <class 'numpy.int8'>:....datetime6...

๐Ÿ“ฆ Dictionary mapping dtype to number of bytes.

๐Ÿ”ข negative = <ufunc 'negative'>

โž– Numerical negative, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> np.negative([1.,-1.])
array([-1.,  1.])

The unary ``-`` operator can be used as a shorthand for ``np.negative`` on
ndarrays.

>>> x1 = np.array(([1., -1.]))
>>> -x1
array([-1.,  1.])

๐Ÿ”ข newaxis = None

๐Ÿ”ข Alias for None used in indexing.

๐Ÿ”ข nextafter = <ufunc 'nextafter'>

โžก๏ธ Return the next floating-point value after x1 towards x2, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> eps = np.finfo(np.float64).eps
>>> np.nextafter(1, 2) == eps + 1
True
>>> np.nextafter([1, 2], [2, 1]) == [eps + 1, 2 - eps]
array([ True,  True])

๐Ÿ”ข not_equal = <ufunc 'not_equal'>

โ‰  Return (x1 != x2) element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.not_equal([1.,2.], [1., 3.])
array([False,  True])
>>> np.not_equal([1, 2], [[1, 3],[1, 4]])
array([[False,  True],
       [False,  True]])

The ``!=`` operator can be used as a shorthand for ``np.not_equal`` on
ndarrays.

>>> a = np.array([1., 2.])
>>> b = np.array([1., 3.])
>>> a != b
array([False,  True])

๐Ÿ”ข ogrid = <numpy.lib.index_tricks.OGridClass object>

๐Ÿ“ An instance of numpy.lib.index_tricks.OGridClass.

๐Ÿ”ข pi = 3.141592653589793

๐Ÿ”ข The mathematical constant ฯ€.

๐Ÿ”ข positive = <ufunc 'positive'>

โž• Numerical positive, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

Equivalent to x.copy(), but only defined for types that support arithmetic.

๐Ÿ’ก Examples

>>> x1 = np.array(([1., -1.]))
>>> np.positive(x1)
array([ 1., -1.])

The unary ``+`` operator can be used as a shorthand for ``np.positive`` on
ndarrays.

>>> x1 = np.array(([1., -1.]))
>>> +x1
array([ 1., -1.])

๐Ÿ”ข power = <ufunc 'power'>

๐Ÿ”ข First array elements raised to powers from second array, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

Cube each element in an array.

>>> x1 = np.arange(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.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.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.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
       [ 0,  1,  8, 27, 16,  5]])

The ``**`` operator can be used as a shorthand for ``np.power`` on
ndarrays.

>>> x2 = np.array([1, 2, 3, 3, 2, 1])
>>> x1 = np.arange(6)
>>> x1 ** x2
array([ 0,  1,  8, 27, 16,  5])

๐Ÿ”ข r_ = <numpy.lib.index_tricks.RClass object>

๐Ÿ“ Translates slice objects to concatenation along the first axis.

๐Ÿ”ข rad2deg = <ufunc 'rad2deg'>

๐Ÿ”„ Convert angles from radians to degrees.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

.. versionadded:: 1.3.0

rad2deg(x) is 180 * x / pi.

๐Ÿ’ก Examples

>>> np.rad2deg(np.pi/2)
90.0

๐Ÿ”ข radians = <ufunc 'radians'>

๐Ÿ”„ Convert angles from degrees to radians.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

Convert a degree array to radians

>>> deg = np.arange(12.) * 30.
>>> np.radians(deg)
array([ 0.        ,  0.52359878,  1.04719755,  1.57079633,  2.0943951 ,
        2.61799388,  3.14159265,  3.66519143,  4.1887902 ,  4.71238898,
        5.23598776,  5.75958653])

>>> out = np.zeros((deg.shape))
>>> ret = np.radians(deg, out)
>>> ret is out
True

๐Ÿ”ข reciprocal = <ufunc 'reciprocal'>

โž— Return the reciprocal of the argument, element-wise. Calculates 1/x.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

.. note:: This function is not designed to work with integers. For integer arguments with absolute value larger than 1 the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow.

๐Ÿ’ก Examples

>>> np.reciprocal(2.)
0.5
>>> np.reciprocal([1, 2., 3.33])
array([ 1.       ,  0.5      ,  0.3003003])

๐Ÿ”ข remainder = <ufunc 'remainder'>

โž— Return element-wise remainder of division. (See mod above for full documentation.)

๐Ÿ”ข right_shift = <ufunc 'right_shift'>

โžก๏ธ Shift the bits of an integer to the right.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.binary_repr(10)
'1010'
>>> np.right_shift(10, 1)
5
>>> np.binary_repr(5)
'101'

>>> np.right_shift(10, [1,2,3])
array([5, 2, 1])

The ``>>`` operator can be used as a shorthand for ``np.right_shift`` on
ndarrays.

>>> x1 = 10
>>> x2 = np.array([1,2,3])
>>> x1 >> x2
array([5, 2, 1])

๐Ÿ”ข rint = <ufunc 'rint'>

๐Ÿ”ข Round elements of the array to the nearest integer.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc.

๐Ÿ’ก Examples

>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.rint(a)
array([-2., -2., -0.,  0.,  2.,  2.,  2.])

๐Ÿ”ข s_ = <numpy.lib.index_tricks.IndexExpression object>

๐Ÿ“ A convenient way to create index expressions.

๐Ÿ”ข sctypeDict = {'?': <class 'numpy.bool_'>, 0: <class 'numpy.bool_'>, 'b...

๐Ÿ“ฆ Dictionary mapping type codes to dtype classes.

๐Ÿ”ข sctypes = {'complex': [<class 'numpy.complex64'>, <class 'numpy.comple...

๐Ÿ“ฆ Dictionary grouping dtype classes by category.

๐Ÿ”ข sign = <ufunc 'sign'>

๐Ÿ”ข Returns an element-wise indication of the sign of a number.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

There is more than one definition of sign in common use for complex numbers. The definition used here is equivalent to x/โˆš(x*x) which is different from a common alternative, x/|x|.

๐Ÿ’ก Examples

>>> np.sign([-5., 4.5])
array([-1.,  1.])
>>> np.sign(0)
0
>>> np.sign(5-2j)
(1+0j)

๐Ÿ”ข signbit = <ufunc 'signbit'>

๐Ÿ”ข Returns element-wise True where signbit is set (less than zero).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ’ก Examples

>>> np.signbit(-1.2)
True
>>> np.signbit(np.array([1, -2.3, 2.1]))
array([False,  True, False])

๐Ÿ”ข sin = <ufunc 'sin'>

๐Ÿ“ Trigonometric sine, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

The sine is one of the fundamental functions of trigonometry (the mathematical study of triangles). Consider a circle of radius 1 centered on the origin. A ray comes in from the +x axis, makes an angle at the origin (measured counter-clockwise from that axis), and departs from the origin. The y coordinate of the outgoing ray's intersection with the unit circle is the sine of that angle. It ranges from -1 for x=3ฯ€/2 to +1 for ฯ€/2. The function has zeroes where the angle is a multiple of ฯ€. Sines of angles between ฯ€ and 2ฯ€ are negative. The numerous properties of the sine and related functions are included in any standard trigonometry text.

๐Ÿ’ก Examples

Print sine of one angle:

>>> np.sin(np.pi/2.)
1.0

Print sines of an array of angles given in degrees:

>>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
array([ 0.        ,  0.5       ,  0.70710678,  0.8660254 ,  1.        ])

Plot the sine function:

>>> import matplotlib.pylab as plt
>>> x = np.linspace(-np.pi, np.pi, 201)
>>> plt.plot(x, np.sin(x))
>>> plt.xlabel('Angle [rad]')
>>> plt.ylabel('sin(x)')
>>> plt.axis('tight')
>>> plt.show()

๐Ÿ”ข sinh = <ufunc 'sinh'>

๐Ÿ“ Hyperbolic sine, element-wise. Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)

๐Ÿ“š References

๐Ÿ’ก Examples

>>> np.sinh(0)
0.0
>>> np.sinh(np.pi*1j/2)
1j
>>> np.sinh(np.pi*1j) # (exact value is 0)
1.2246063538223773e-016j
>>> # Discrepancy due to vagaries of floating point arithmetic.

>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.sinh([0.1], out1)
>>> out2 is out1
True

>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.sinh(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)

๐Ÿ”ข spacing = <ufunc 'spacing'>

๐Ÿ“ Return the distance between x and the nearest adjacent number.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

It can be considered as a generalization of EPS: spacing(np.float64(1)) == np.finfo(np.float64).eps, and there should not be any representable number between x + spacing(x) and x for any finite x. Spacing of ยฑinf and NaN is NaN.

๐Ÿ’ก Examples

>>> np.spacing(1) == np.finfo(np.float64).eps
True

๐Ÿ”ข sqrt = <ufunc 'sqrt'>

โˆš Return the non-negative square-root of an array, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

sqrt hasโ€”consistent with common conventionโ€”as its branch cut the real "interval" [-inf, 0), and is continuous from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be continuous.

๐Ÿ’ก Examples

>>> np.sqrt([1,4,9])
array([ 1.,  2.,  3.])

>>> np.sqrt([4, -1, -3+4J])
array([ 2.+0.j,  0.+1.j,  1.+2.j])

>>> np.sqrt([4, -1, np.inf])
array([ 2., nan, inf])

๐Ÿ”ข square = <ufunc 'square'>

๐Ÿ”ข Return the element-wise square of the input.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ’ก Examples

>>> np.square([-1j, 1])
array([-1.-0.j,  1.+0.j])

๐Ÿ”ข subtract = <ufunc 'subtract'>

โž– Subtract arguments, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

Equivalent to x1 - x2 in terms of array broadcasting.

๐Ÿ’ก Examples

>>> np.subtract(1.0, 4.0)
-3.0

>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.subtract(x1, x2)
array([[ 0.,  0.,  0.],
       [ 3.,  3.,  3.],
       [ 6.,  6.,  6.]])

The ``-`` operator can be used as a shorthand for ``np.subtract`` on
ndarrays.

>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 - x2
array([[0., 0., 0.],
       [3., 3., 3.],
       [6., 6., 6.]])

๐Ÿ”ข tan = <ufunc 'tan'>

๐Ÿ“ Compute tangent element-wise. Equivalent to np.sin(x)/np.cos(x).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)

๐Ÿ“š References

๐Ÿ’ก Examples

>>> from math import pi
>>> np.tan(np.array([-pi,pi/2,pi]))
array([  1.22460635e-16,   1.63317787e+16,  -1.22460635e-16])
>>>
>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.cos([0.1], out1)
>>> out2 is out1
True
>>>
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.cos(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)

๐Ÿ”ข tanh = <ufunc 'tanh'>

๐Ÿ“ Compute hyperbolic tangent element-wise. Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ Notes

If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)

๐Ÿ“š References

๐Ÿ’ก Examples

>>> np.tanh((0, np.pi*1j, np.pi*1j/2))
array([ 0. +0.00000000e+00j,  0. -1.22460635e-16j,  0. +1.63317787e+16j])

>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.tanh([0.1], out1)
>>> out2 is out1
True

>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.tanh(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)

๐Ÿ”ข tracemalloc_domain = 389047

๐Ÿ”ข Domain identifier for tracemalloc.

๐Ÿ”ข true_divide = <ufunc 'true_divide'>

โž— Returns a true division of the inputs, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ“ 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.  ])

๐Ÿ”ข trunc = <ufunc 'trunc'>

๐Ÿ”ข Return the truncated value of the input, element-wise.

๐Ÿ“ฅ Parameters

๐Ÿ“ค Returns

๐Ÿ‘€ See Also

๐Ÿ“ Notes

.. versionadded:: 1.3.0

๐Ÿ’ก Examples

>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0.,  0.,  1.,  1.,  2.])

๐Ÿ”ข typecodes = {'All': '?bhilqpBHILQPefdgFDGSUVOMm', 'AllFloat': 'efdgFDG...

๐Ÿ“ฆ Dictionary mapping type categories to strings of type codes.

๐Ÿ“ฆ VERSION

1.21.5

๐Ÿ“ FILE

/usr/lib/python3/dist-packages/numpy/__init__.py
numpy
๐Ÿ“– NAME ๐Ÿ“– DESCRIPTION
๐Ÿ“š How to use the documentation ๐Ÿ“ฆ Available subpackages ๐Ÿ”ง Utilities ๐Ÿ’ป Viewing documentation using IPython ๐Ÿ“ Copies vs. in-place operation
๐Ÿ“ฆ PACKAGE CONTENTS ๐Ÿ“ฆ Submodules ๐Ÿ“ฆ CLASSES
โš ๏ธ AxisError โš ๏ธ ComplexWarning ๐Ÿ“‚ DataSource โš™๏ธ MachAr โš ๏ธ ModuleDeprecationWarning โš ๏ธ RankWarning โŒ TooHardError โš ๏ธ VisibleDeprecationWarning ๐Ÿ”  bool_ (numpy.bool8) ๐Ÿ”ง broadcast ๐Ÿ“… busdaycalendar ๐Ÿ”ข int8 (numpy.byte) ๐Ÿ”ค bytes_ (numpy.string_) ๐Ÿ”ข int types (int8, int16, int32, int64, uint8, uint16, uint32, uint64, longlong, ulonglong, etc.) ๐Ÿ”ข float types (float16, float32, float64, float128, complex64, complex128, complex256) ๐Ÿ”  str_ (numpy.str_) ๐Ÿ“ฆ generic ๐Ÿ“ฆ flexible, character, void, record ๐Ÿ”ข number, integer, signedinteger, unsignedinteger, inexact, floating, complexfloating ๐Ÿ“ฆ object_ ๐Ÿ“ฆ datetime64, timedelta64 ๐Ÿ“ฆ dtype, finfo, iinfo, flatiter, format_parser, ndarray, chararray, matrix, memmap, recarray, ndenumerate, ndindex, nditer, poly1d, ufunc, vectorize, errstate
๐Ÿงฌ CLASSES
๐Ÿ“ฆ class bytes(builtins.bytes) ๐Ÿงช class complex128(complexfloating, builtins.complex) ๐Ÿงช class complex128 (alias: cfloat) ๐Ÿ”ค class character(flexible) ๐Ÿ“ class chararray(ndarray)
๐Ÿ“ฆ CLASSES
๐Ÿ“˜ ndarray ๐Ÿ“˜ clongdouble = class complex256(complexfloating) ๐Ÿ“˜ clongfloat = class complex256(complexfloating) ๐Ÿ“˜ complex128 (complexfloating, builtins.complex) ๐Ÿ“˜ complex256 (complexfloating) ๐Ÿ“˜ complex64 (complexfloating) ๐Ÿ“˜ complex_ = class complex128(complexfloating, builtins.complex) ๐Ÿ“˜ complexfloating (inexact) ๐Ÿ“˜ csingle = class complex64(complexfloating)
๐Ÿ“š CLASSES
๐Ÿ”ง class complexfloating ๐Ÿ“… class datetime64(generic) ๐Ÿ”ข class float64 (double) ๐Ÿท๏ธ class dtype(builtins.object) โš ๏ธ class errstate(contextlib.ContextDecorator) ๐Ÿ”ฌ class finfo(builtins.object) ๐Ÿ”„ class flatiter(builtins.object) ๐Ÿงฉ class flexible(generic) ๐Ÿ”ข class float128(floating) ๐Ÿ”ข class float16(floating) ๐Ÿ”ข class float32(floating)
๐Ÿ›๏ธ CLASSES
๐Ÿงฌ class float64(floating, builtins.float) ๐Ÿงฌ class floating(inexact) ๐Ÿงฌ class format_parser(builtins.object) ๐Ÿงฌ class generic(builtins.object) ๐Ÿงฌ half = class float16(floating) ๐Ÿงฌ class iinfo(builtins.object) ๐Ÿงฌ class inexact(number) ๐Ÿงฌ int0 = class int64(signedinteger)
๐Ÿ“š CLASSES
class int8(signedinteger) class int16(signedinteger) class int32(signedinteger) class int64(signedinteger) class integer(number) int_ = class int64 (signedinteger) intc = class int32 (signedinteger) intp = class int64 (signedinteger) longcomplex = class complex256(complexfloating)
๐Ÿ“š CLASSES
๐Ÿ›๏ธ csingle = class complex64 ๐Ÿ›๏ธ cdouble = class complex128 ๐Ÿ›๏ธ cfloat = class complex128 ๐Ÿ›๏ธ clongdouble = class complex192 (on Linux x86_64) ๐Ÿ›๏ธ clongfloat = class complex192 (on Linux x86_64) ๐Ÿ›๏ธ complex64 = class complex64 ๐Ÿ›๏ธ complex128 = class complex128 ๐Ÿ›๏ธ complex192 = class complex192 ๐Ÿ›๏ธ complex256 = class complex256 ๐Ÿ›๏ธ compound = class generic
๐Ÿ“š CLASSES
๐Ÿ› ๏ธ ndarray Methods ๐Ÿ“Š Data Descriptors inherited from ndarray ๐Ÿงฉ class memmap ๐Ÿ—๏ธ class ndarray
๐Ÿ“ฆ CLASSES
๐Ÿ”ง ndarray ๐Ÿ”ง ndenumerate ๐Ÿ”ง ndindex ๐Ÿ”ง nditer ๐Ÿ”ง number ๐Ÿ”ง object_
๐Ÿ“ฆ CLASSES
๐Ÿ”ง class generic(builtins.object) ๐Ÿ”ง class poly1d(builtins.object) ๐Ÿ”ง class recarray(ndarray) ๐Ÿ”ง class record(void) ๐Ÿ”ง class short = int16(signedinteger)
๐Ÿ“š CLASSES
๐Ÿ“ฆ generic ๐Ÿ”ข signedinteger ๐Ÿ’ง float32 (single precision) ๐ŸŒ€ complex64 (singlecomplex) ๐Ÿ“ str0 (str_) ๐Ÿ“œ string_ (bytes_)
๐Ÿงฉ CLASSES
๐Ÿ”น generic (from builtins.object) ๐Ÿ”น timedelta64 (signedinteger) ๐Ÿ”น ufunc (builtins.object) ๐Ÿ”น uint8 (unsignedinteger) โ€” alias: ubyte ๐Ÿ”น uint16 (unsignedinteger) โ€” alias: ushort ๐Ÿ”น uint32 (unsignedinteger) โ€” alias: uintc ๐Ÿ”น uint64 (unsignedinteger) โ€” aliases: uint, uint0
๐Ÿ“ฆ CLASSES
๐Ÿ”ง Scalar Methods & Data Descriptors (Continuation) ๐Ÿ”ข class uint64 (inherits from unsignedinteger) ๐Ÿ”ข class uint8 (inherits from unsignedinteger) ๐Ÿ”ข class uintc (alias for uint32, inherits from unsignedinteger) ๐Ÿ”ข class uintp (alias for uint64, inherits from unsignedinteger) ๐Ÿ”ข class ulonglong (inherits from unsignedinteger) ๐Ÿ”ข class unicode_ (inherits from builtins.str and character) ๐Ÿ”ข class unsignedinteger (inherits from integer)
๐Ÿ“ฆ CLASSES
๐Ÿ”ข ushort = class uint16(unsignedinteger) ๐Ÿ”„ vectorize = class vectorize(builtins.object) ๐Ÿ“ฆ void = class void(flexible) ๐Ÿ“ฆ void0 = class void(flexible)
๐Ÿ”ง FUNCTIONS
__dir__() __getattr__(attr) _add_newdoc_ufunc(...) add_docstring(...) add_newdoc(place, obj, doc, warn_on_python=True) add_newdoc_ufunc = _add_newdoc_ufunc(...) alen(a) all(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>) allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False) alltrue(*args, **kwargs) amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>) amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>) angle(z, deg=False) any(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>) append(arr, values, axis=None) apply_along_axis(func1d, axis, arr, *args, **kwargs) apply_over_axes(func, a, axes) arange(...) argmax(a, axis=None, out=None) argmin(a, axis=None, out=None) argpartition(a, kth, axis=-1, kind='introselect', order=None) argsort(a, axis=-1, kind=None, order=None) argwhere(a) around(a, decimals=0, out=None) array(...) array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix='', style=<no value>, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix='', *, legacy=None) array_equal(a1, a2, equal_nan=False) array_equiv(a1, a2) array_repr(arr, max_line_width=None, precision=None, suppress_small=None) array_split(ary, indices_or_sections, axis=0) array_str(a, max_line_width=None, precision=None, suppress_small=None) asanyarray(...) asarray(...) asarray_chkfinite(a, dtype=None, order=None) ascontiguousarray(...) asfarray(a, dtype=<class 'numpy.float64'>) asfortranarray(...) asmatrix(data, dtype=None) asscalar(a) atleast_1d(*arys) atleast_2d(*arys) atleast_3d(*arys) average(a, axis=None, weights=None, returned=False) bartlett(M) base_repr(number, base=2, padding=0) binary_repr(num, width=None) bincount(...) blackman(M) block(arrays) bmat(obj, ldict=None, gdict=None) broadcast_arrays(*args, subok=False) broadcast_shapes(*args) broadcast_to(array, shape, subok=False) busday_count(...) busday_offset(...) byte_bounds(a) can_cast(...) choose(a, choices, out=None, mode='raise')
๐Ÿงฉ FUNCTIONS
๐Ÿ”น choose ๐Ÿ”น clip ๐Ÿ”น column_stack ๐Ÿ”น common_type ๐Ÿ”น compare_chararrays ๐Ÿ”น compress ๐Ÿ”น concatenate ๐Ÿ”น convolve ๐Ÿ”น copy ๐Ÿ”น copyto ๐Ÿ”น corrcoef ๐Ÿ”น correlate ๐Ÿ”น count_nonzero ๐Ÿ”น cov ๐Ÿ”น cross ๐Ÿ”น cumprod ๐Ÿ”น cumproduct ๐Ÿ”น cumsum ๐Ÿ”น datetime_as_string ๐Ÿ”น datetime_data ๐Ÿ”น delete ๐Ÿ”น deprecate ๐Ÿ”น deprecate_with_doc ๐Ÿ”น diag ๐Ÿ”น diag_indices ๐Ÿ”น diag_indices_from ๐Ÿ”น diagflat ๐Ÿ”น diagonal ๐Ÿ”น diff ๐Ÿ”น digitize ๐Ÿ”น disp ๐Ÿ”น dot ๐Ÿ”น dsplit ๐Ÿ”น dstack ๐Ÿ”น ediff1d ๐Ÿ”น einsum ๐Ÿ”น einsum_path ๐Ÿ”น empty ๐Ÿ”น empty_like ๐Ÿ”น expand_dims ๐Ÿ”น extract ๐Ÿ”น eye ๐Ÿ”น fill_diagonal ๐Ÿ”น find_common_type ๐Ÿ”น fix ๐Ÿ”น flatnonzero ๐Ÿ”น flip ๐Ÿ”น fliplr ๐Ÿ”น flipud ๐Ÿ”น format_float_positional ๐Ÿ”น format_float_scientific ๐Ÿ”น frombuffer
โš™๏ธ FUNCTIONS
๐Ÿงฑ frombuffer(...) ๐Ÿ“„ fromfile(...) ๐Ÿ—๏ธ fromfunction(function, shape, *, dtype=None, like=None, **kwargs) ๐Ÿ”„ fromiter(...) ๐ŸŽฎ frompyfunc(...) ๐Ÿ” fromregex(file, regexp, dtype, encoding=None) ๐Ÿ“ fromstring(...) ๐Ÿ”ฒ full(shape, fill_value, dtype=None, order='C', *, like=None) ๐Ÿ”ณ full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None) ๐Ÿ“‹ genfromtxt(fname, dtype=<class 'float'>, ...) ๐Ÿ“ geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0) ๐ŸŽ get_array_wrap(*args) ๐Ÿ“ get_include() ๐Ÿ–จ๏ธ get_printoptions() ๐Ÿ“ฆ getbufsize() โš ๏ธ geterr() ๐Ÿ“ž geterrcall() ๐Ÿงฉ geterrobj(...) ๐Ÿ“‰ gradient(f, *varargs, axis=None, edge_order=1) ๐ŸŒŠ hamming(M) ใ€ฐ๏ธ hanning(M) ๐Ÿ“Š histogram(a, bins=10, range=None, normed=None, weights=None, density=None) ๐Ÿ—บ๏ธ histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None) ๐Ÿ“ histogram_bin_edges(a, bins=10, range=None, weights=None) ๐ŸงŠ histogramdd(sample, bins=10, range=None, normed=None, weights=None, density=None) โœ‚๏ธ hsplit(ary, indices_or_sections) ๐Ÿ“š hstack(tup) ๐Ÿ”ฌ i0(x) ๐Ÿชช identity(n, dtype=None, *, like=None) ๐Ÿ’ญ imag(val) ๐Ÿ”Ž in1d(ar1, ar2, assume_unique=False, invert=False) ๐Ÿ“‘ indices(dimensions, dtype=<class 'int'>, sparse=False) โ„น๏ธ info(object=None, maxwidth=76, output=<_io.TextIOWrapper ...>, toplevel='numpy') ๐Ÿ“ inner(...) ๐Ÿ“Œ insert(arr, obj, values, axis=None) ๐Ÿ“ˆ interp(x, xp, fp, left=None, right=None, period=None) ๐Ÿ”— intersect1d(ar1, ar2, assume_unique=False, return_indices=False) ๐Ÿ“… is_busday(...) ๐ŸŽฏ isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False) ๐Ÿ”ฎ iscomplex(x) ๐Ÿงฌ iscomplexobj(x) ๐Ÿฐ isfortran(a) ๐Ÿ”Ž isin(element, test_elements, assume_unique=False, invert=False) โ›” isneginf(x, out=None) โ™พ๏ธ isposinf(x, out=None) ๐Ÿงพ isreal(x) ๐Ÿ“ฆ isrealobj(x) โš›๏ธ isscalar(element) ๐Ÿงฌ issctype(rep) ๐Ÿ“Ž issubclass_(arg1, arg2) ๐Ÿงญ issubdtype(arg1, arg2) ๐Ÿ”ฌ issubsctype(arg1, arg2) ๐Ÿ”„ iterable(y)
๐Ÿ”ง FUNCTIONS
๐Ÿ“– percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False) ๐Ÿ“– piecewise(x, condlist, funclist, *args, **kw) ๐Ÿ“– place(arr, mask, vals) ๐Ÿ“– poly(seq_of_zeros) ๐Ÿ“– polyadd(a1, a2) ๐Ÿ“– polyder(p, m=1) ๐Ÿ“– polydiv(u, v) ๐Ÿ“– polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False) ๐Ÿ“– polyint(p, m=1, k=None) ๐Ÿ“– polymul(a1, a2) ๐Ÿ“– polysub(a1, a2) ๐Ÿ“– polyval(p, x) ๐Ÿ“– printoptions(*args, **kwargs) ๐Ÿ“– prod(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>) ๐Ÿ“– product(*args, **kwargs) ๐Ÿ“– promote_types(type1, type2) ๐Ÿ“– ptp(a, axis=None, out=None, keepdims=<no value>) ๐Ÿ“– put(a, ind, v, mode='raise') ๐Ÿ“– put_along_axis(arr, indices, values, axis) ๐Ÿ“– putmask(a, mask, values) ๐Ÿ“– quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False) ๐Ÿ“– ravel(a, order='C') ๐Ÿ“– ravel_multi_index(multi_index, dims, mode='raise', order='C') ๐Ÿ“– real(val) ๐Ÿ“– real_if_close(a, tol=100) ๐Ÿ“– recfromcsv(fname, **kwargs) ๐Ÿ“– recfromtxt(fname, **kwargs) ๐Ÿ“– repeat(a, repeats, axis=None) ๐Ÿ“– require(a, dtype=None, requirements=None, *, like=None) ๐Ÿ“– reshape(a, newshape, order='C') ๐Ÿ“– resize(a, new_shape) ๐Ÿ“– result_type(*arrays_and_dtypes) ๐Ÿ“– roll(a, shift, axis=None) ๐Ÿ“– rollaxis(a, axis, start=0) ๐Ÿ“– roots(p) ๐Ÿ“– rot90(m, k=1, axes=(0, 1)) ๐Ÿ“– round_(a, decimals=0, out=None) ๐Ÿ“– row_stack = vstack(tup) ๐Ÿ“– safe_eval(source) ๐Ÿ“– save(file, arr, allow_pickle=True, fix_imports=True) ๐Ÿ“– savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None) ๐Ÿ“– savez(file, *args, **kwds) ๐Ÿ“– savez_compressed(file, *args, **kwds) ๐Ÿ“– sctype2char(sctype) ๐Ÿ“– searchsorted(a, v, side='left', sorter=None) ๐Ÿ“– select(condlist, choicelist, default=0) ๐Ÿ“– set_numeric_ops(op1=func1, op2=func2, ...) ๐Ÿ“– set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None) ๐Ÿ“– set_string_function(f, repr=True) ๐Ÿ“– setbufsize(size) ๐Ÿ“– setdiff1d(ar1, ar2, assume_unique=False) ๐Ÿ“– seterr(all=None, divide=None, over=None, under=None, invalid=None) ๐Ÿ“– seterrcall(func) ๐Ÿ“– seterrobj(errobj) ๐Ÿ“– setxor1d(ar1, ar2, assume_unique=False) ๐Ÿ“– shape(a) ๐Ÿ“– shares_memory(a, b, max_work=None) ๐Ÿ“– show_config = show()
๐Ÿ”ง FUNCTIONS
๐Ÿ“– show_config() ๐Ÿ“– sinc(x) ๐Ÿ“– size(a, axis=None) ๐Ÿ“– sometrue(*args, **kwargs) ๐Ÿ“– sort(a, axis=-1, kind=None, order=None) ๐Ÿ“– sort_complex(a) ๐Ÿ“– source(object, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) ๐Ÿ“– split(ary, indices_or_sections, axis=0) ๐Ÿ“– squeeze(a, axis=None) ๐Ÿ“– stack(arrays, axis=0, out=None) ๐Ÿ“– std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>) ๐Ÿ“– sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>) ๐Ÿ“– swapaxes(a, axis1, axis2) ๐Ÿ“– take(a, indices, axis=None, out=None, mode='raise') ๐Ÿ“– take_along_axis(arr, indices, axis) ๐Ÿ“– tensordot(a, b, axes=2) ๐Ÿ“– tile(A, reps) ๐Ÿ“– trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None) ๐Ÿ“– transpose(a, axes=None) ๐Ÿ“– trapz(y, x=None, dx=1.0, axis=-1) ๐Ÿ“– tri(N, M=None, k=0, dtype=<class 'float'>, *, like=None) ๐Ÿ“– tril(m, k=0) ๐Ÿ“– tril_indices(n, k=0, m=None) ๐Ÿ“– tril_indices_from(arr, k=0) ๐Ÿ“– trim_zeros(filt, trim='fb') ๐Ÿ“– triu(m, k=0) ๐Ÿ“– triu_indices(n, k=0, m=None) ๐Ÿ“– triu_indices_from(arr, k=0) ๐Ÿ“– typename(char) ๐Ÿ“– union1d(ar1, ar2) ๐Ÿ“– unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None) ๐Ÿ“– unpackbits(...) ๐Ÿ“– unravel_index(...) ๐Ÿ“– unwrap(p, discont=None, axis=-1, *, period=6.283185307179586) ๐Ÿ“– vander(x, N=None, increasing=False) ๐Ÿ“– var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>) ๐Ÿ“– vdot(...) ๐Ÿ“– vsplit(ary, indices_or_sections) ๐Ÿ“– vstack(tup) ๐Ÿ“– where(...) ๐Ÿ“– who(vardict=None) ๐Ÿ“– zeros(...) ๐Ÿ“– zeros_like(a, dtype=None, order='K', subok=True, shape=None)
๐Ÿ“Š DATA
๐Ÿ”ข Constants ๐Ÿ”ง Ufuncs
๐Ÿ“Š Data
๐Ÿ”ข log10 = <ufunc 'log10'> ๐Ÿ”ข log1p = <ufunc 'log1p'> ๐Ÿ”ข log2 = <ufunc 'log2'> ๐Ÿ”ข logaddexp = <ufunc 'logaddexp'> ๐Ÿ”ข logaddexp2 = <ufunc 'logaddexp2'> ๐Ÿ”ข logical_and = <ufunc 'logical_and'> ๐Ÿ”ข logical_not = <ufunc 'logical_not'> ๐Ÿ”ข logical_or = <ufunc 'logical_or'> ๐Ÿ”ข logical_xor = <ufunc 'logical_xor'> ๐Ÿ”ข matmul = <ufunc 'matmul'> ๐Ÿ”ข maximum = <ufunc 'maximum'> ๐Ÿ”ข mgrid = <numpy.lib.index_tricks.MGridClass object> ๐Ÿ”ข minimum = <ufunc 'minimum'> ๐Ÿ”ข mod = <ufunc 'remainder'> ๐Ÿ”ข modf = <ufunc 'modf'> ๐Ÿ”ข multiply = <ufunc 'multiply'> ๐Ÿ”ข nan = nan ๐Ÿ”ข nbytes = {<class 'numpy.bool_'>: 1, <class 'numpy.int8'>:....datetime6... ๐Ÿ”ข negative = <ufunc 'negative'> ๐Ÿ”ข newaxis = None ๐Ÿ”ข nextafter = <ufunc 'nextafter'> ๐Ÿ”ข not_equal = <ufunc 'not_equal'> ๐Ÿ”ข ogrid = <numpy.lib.index_tricks.OGridClass object> ๐Ÿ”ข pi = 3.141592653589793 ๐Ÿ”ข positive = <ufunc 'positive'> ๐Ÿ”ข power = <ufunc 'power'> ๐Ÿ”ข r_ = <numpy.lib.index_tricks.RClass object> ๐Ÿ”ข rad2deg = <ufunc 'rad2deg'> ๐Ÿ”ข radians = <ufunc 'radians'> ๐Ÿ”ข reciprocal = <ufunc 'reciprocal'> ๐Ÿ”ข remainder = <ufunc 'remainder'> ๐Ÿ”ข right_shift = <ufunc 'right_shift'> ๐Ÿ”ข rint = <ufunc 'rint'> ๐Ÿ”ข s_ = <numpy.lib.index_tricks.IndexExpression object> ๐Ÿ”ข sctypeDict = {'?': <class 'numpy.bool_'>, 0: <class 'numpy.bool_'>, 'b... ๐Ÿ”ข sctypes = {'complex': [<class 'numpy.complex64'>, <class 'numpy.comple... ๐Ÿ”ข sign = <ufunc 'sign'> ๐Ÿ”ข signbit = <ufunc 'signbit'> ๐Ÿ”ข sin = <ufunc 'sin'> ๐Ÿ”ข sinh = <ufunc 'sinh'> ๐Ÿ”ข spacing = <ufunc 'spacing'> ๐Ÿ”ข sqrt = <ufunc 'sqrt'> ๐Ÿ”ข square = <ufunc 'square'> ๐Ÿ”ข subtract = <ufunc 'subtract'> ๐Ÿ”ข tan = <ufunc 'tan'> ๐Ÿ”ข tanh = <ufunc 'tanh'> ๐Ÿ”ข tracemalloc_domain = 389047 ๐Ÿ”ข true_divide = <ufunc 'true_divide'> ๐Ÿ”ข trunc = <ufunc 'trunc'> ๐Ÿ”ข typecodes = {'All': '?bhilqpBHILQPefdgFDGSUVOMm', 'AllFloat': 'efdgFDG...
๐Ÿ“ฆ VERSION ๐Ÿ“ FILE

Generated by phpman v4.10.0-7-g98e9fd5 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-03 19:00 @216.73.216.23
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!

^_top_^