Many people like to say that Python is a fantastic glue language. Hopefully, this Chapter will convince you that this is true. The first adopters of Python for science were typically people who used it to glue together large application codes running on super-computers. Not only was it much nicer to code in Python than in a shell script or Perl, in addition, the ability to easily extend Python made it relatively easy to create new classes and types specifically adapted to the problems being solved. From the interactions of these early contributors, Numeric emerged as an array-like object that could be used to pass data between these applications.
As Numeric has matured and developed into NumPy, people have been able to write more code directly in NumPy. Often this code is fast-enough for production use, but there are still times that there is a need to access compiled code. Either to get that last bit of efficiency out of the algorithm or to make it easier to access widely-available codes written in C/C++ or Fortran.
This chapter will review many of the tools that are available for the purpose of accessing code written in other compiled languages. There are many resources available for learning to call other compiled libraries from Python and the purpose of this Chapter is not to make you an expert. The main goal is to make you aware of some of the possibilities so that you will know what to “Google” in order to learn more.
While Python is a great language and a pleasure to code in, its dynamic nature results in overhead that can cause some code ( i.e. raw computations inside of for loops) to be up 10-100 times slower than equivalent code written in a static compiled language. In addition, it can cause memory usage to be larger than necessary as temporary arrays are created and destroyed during computation. For many types of computing needs, the extra slow-down and memory consumption can often not be spared (at least for time- or memory- critical portions of your code). Therefore one of the most common needs is to call out from Python code to a fast, machine-code routine (e.g. compiled using C/C++ or Fortran). The fact that this is relatively easy to do is a big reason why Python is such an excellent high-level language for scientific and engineering programming.
Their are two basic approaches to calling compiled code: writing an extension module that is then imported to Python using the import command, or calling a shared-library subroutine directly from Python using the ctypes module. Writing an extension module is the most common method.
Warning
Calling C-code from Python can result in Python crashes if you are not careful. None of the approaches in this chapter are immune. You have to know something about the way data is handled by both NumPy and by the third-party library being used.
Extension modules were discussed in Writing an extension module. The most basic way to interface with compiled code is to write an extension module and construct a module method that calls the compiled code. For improved readability, your method should take advantage of the PyArg_ParseTuple call to convert between Python objects and C data-types. For standard C data-types there is probably already a built-in converter. For others you may need to write your own converter and use the "O&" format string which allows you to specify a function that will be used to perform the conversion from the Python object to whatever C-structures are needed.
Once the conversions to the appropriate C-structures and C data-types have been performed, the next step in the wrapper is to call the underlying function. This is straightforward if the underlying function is in C or C++. However, in order to call Fortran code you must be familiar with how Fortran subroutines are called from C/C++ using your compiler and platform. This can vary somewhat platforms and compilers (which is another reason f2py makes life much simpler for interfacing Fortran code) but generally involves underscore mangling of the name and the fact that all variables are passed by reference (i.e. all arguments are pointers).
The advantage of the hand-generated wrapper is that you have complete control over how the C-library gets used and called which can lead to a lean and tight interface with minimal over-head. The disadvantage is that you have to write, debug, and maintain C-code, although most of it can be adapted using the time-honored technique of “cutting-pasting-and-modifying” from other extension modules. Because, the procedure of calling out to additional C-code is fairly regimented, code-generation procedures have been developed to make this process easier. One of these code-generation techniques is distributed with NumPy and allows easy integration with Fortran and (simple) C code. This package, f2py, will be covered briefly in the next section.
F2py allows you to automatically construct an extension module that interfaces to routines in Fortran 77/90/95 code. It has the ability to parse Fortran 77/90/95 code and automatically generate Python signatures for the subroutines it encounters, or you can guide how the subroutine interfaces with Python by constructing an interface-definition-file (or modifying the f2py-produced one).
Probably the easiest way to introduce f2py is to offer a simple example. Here is one of the subroutines contained in a file named add.f
This routine simply adds the elements in two contiguous arrays and places the result in a third. The memory for all three arrays must be provided by the calling routine. A very basic interface to this routine can be automatically generated by f2py:
You should be able to run this command assuming your search-path is set-up properly. This command will produce an extension module named addmodule.c in the current directory. This extension module can now be compiled and used from Python just like any other extension module.
You can also get f2py to both compile add.f along with the produced extension module leaving only a shared-library extension file that can be imported from Python:
This command leaves a file named add.{ext} in the current directory (where {ext} is the appropriate extension for a Python extension module on your platform — so, pyd, etc. ). This module may then be imported from Python. It will contain a method for each subroutine in add (zadd, cadd, dadd, sadd). The docstring of each method contains information about how the module method may be called:
The default interface is a very literal translation of the Fortran code into Python. The Fortran array arguments must now be NumPy arrays and the integer argument should be an integer. The interface will attempt to convert all arguments to their required types (and shapes) and issue an error if unsuccessful. However, because it knows nothing about the semantics of the arguments (such that C is an output and n should really match the array sizes), it is possible to abuse this function in ways that can cause Python to crash. For example:
will cause a program crash on most systems. Under the covers, the lists are being converted to proper arrays but then the underlying add loop is told to cycle way beyond the borders of the allocated memory.
In order to improve the interface, directives should be provided. This is accomplished by constructing an interface definition file. It is usually best to start from the interface file that f2py can produce (where it gets its default behavior from). To get f2py to generate the interface file use the -h option:
This command leaves the file add.pyf in the current directory. The section of this file corresponding to zadd is:
By placing intent directives and checking code, the interface can be cleaned up quite a bit until the Python module method is both easier to use and more robust.
The intent directive, intent(out) is used to tell f2py that c is an output variable and should be created by the interface before being passed to the underlying code. The intent(hide) directive tells f2py to not allow the user to specify the variable, n, but instead to get it from the size of a. The depend( a ) directive is necessary to tell f2py that the value of n depends on the input a (so that it won’t try to create the variable n until the variable a is created).
After modifying add.pyf, the new Python module file can be generated by compiling both add.f and add.pyf:
The new interface has docstring:
Now, the function can be called in a much more robust way:
Notice the automatic conversion to the correct format that occurred.
The nice interface can also be generated automatically by placing the variable directives as special comments in the original Fortran code. Thus, if the source code is modified to contain:
Then, one can compile the extension module using:
The resulting signature for the function add.zadd is exactly the same one that was created previously. If the original source code had contained A(N) instead of A(*) and so forth with B and C, then nearly the same interface can be obtained by placing the INTENT(OUT) :: C comment line in the source code. The only difference is that N would be an optional input that would default to the length of A.
For comparison with the other methods to be discussed. Here is another example of a function that filters a two-dimensional array of double precision floating-point numbers using a fixed averaging filter. The advantage of using Fortran to index into multi-dimensional arrays should be clear from this example.
This code can be compiled and linked into an extension module named filter using:
This will produce an extension module named filter.so in the current directory with a method named dfilter2d that returns a filtered version of the input.
The f2py program is written in Python and can be run from inside your code to compile Fortran code at runtime, as follows:
The source string can be any valid Fortran code. If you want to save the extension-module source code then a suitable file-name can be provided by the source_fn keyword to the compile function.
If you want to distribute your f2py extension module, then you only need to include the .pyf file and the Fortran code. The distutils extensions in NumPy allow you to define an extension module entirely in terms of this interface file. A valid setup.py file allowing distribution of the add.f module (as part of the package f2py_examples so that it would be loaded as f2py_examples.add) is:
Installation of the new package is easy using:
assuming you have the proper permissions to write to the main site- packages directory for the version of Python you are using. For the resulting package to work, you need to create a file named __init__.py (in the same directory as add.pyf). Notice the extension module is defined entirely in terms of the add.pyf and add.f files. The conversion of the .pyf file to a .c file is handled by numpy.disutils.
The interface definition file (.pyf) is how you can fine-tune the interface between Python and Fortran. There is decent documentation for f2py at F2PY user guide and reference manual. There is also more information on using f2py (including how to use it to wrap C codes) at the “Interfacing With Other Languages” heading of the SciPy Cookbook.
The f2py method of linking compiled code is currently the most sophisticated and integrated approach. It allows clean separation of Python with compiled code while still allowing for separate distribution of the extension module. The only draw-back is that it requires the existence of a Fortran compiler in order for a user to install the code. However, with the existence of the free-compilers g77, gfortran, and g95, as well as high-quality commercial compilers, this restriction is not particularly onerous. In our opinion, Fortran is still the easiest way to write fast and clear code for scientific computing. It handles complex numbers, and multi-dimensional indexing in the most straightforward way. Be aware, however, that some Fortran compilers will not be able to optimize code as well as good hand- written C-code.
Cython is a compiler for a Python dialect that adds (optional) static typing for speed, and allows mixing C or C++ code into your modules. It produces C or C++ extensions that can be compiled and imported in Python code.
If you are writing an extension module that will include quite a bit of your own algorithmic code as well, then Cython is a good match. Among its features is the ability to easily and quickly work with multidimensional arrays.
Notice that Cython is an extension-module generator only. Unlike f2py, it includes no automatic facility for compiling and linking the extension module (which must be done in the usual fashion). It does provide a modified distutils class called build_ext which lets you build an extension module from a .pyx source. Thus, you could write in a setup.py file:
Adding the NumPy include directory is, of course, only necessary if you are using NumPy arrays in the extension module (which is what we assume you are using Cython for). The distutils extensions in NumPy also include support for automatically producing the extension-module and linking it from a .pyx file. It works so that if the user does not have Cython installed, then it looks for a file with the same file-name but a .c extension which it then uses instead of trying to produce the .c file again.
If you just use Cython to compile a standard Python module, then you will get a C extension module that typically runs a bit faster than the equivalent Python module. Further speed increases can be gained by using the cdef keyword to statically define C variables.
Let’s look at two examples we’ve seen before to see how they might be implemented using Cython. These examples were compiled into extension modules using Cython 0.21.1.
Here is part of a Cython module named add.pyx which implements the complex addition functions we previously implemented using f2py:
This module shows use of the cimport statement to load the definitions from the numpy.pxd header that ships with Cython. It looks like NumPy is imported twice; cimport only makes the NumPy C-API available, while the regular import causes a Python-style import at runtime and makes it possible to call into the familiar NumPy Python API.
The example also demonstrates Cython’s “typed memoryviews”, which are like NumPy arrays at the C level, in the sense that they are shaped and strided arrays that know their own extent (unlike a C array addressed through a bare pointer). The syntax double complex[:] denotes a one-dimensional array (vector) of doubles, with arbitrary strides. A contiguous array of ints would be int[::1], while a matrix of floats would be float[:, :].
Shown commented is the cython.boundscheck decorator, which turns bounds-checking for memory view accesses on or off on a per-function basis. We can use this to further speed up our code, at the expense of safety (or a manual check prior to entering the loop).
Other than the view syntax, the function is immediately readable to a Python programmer. Static typing of the variable i is implicit. Instead of the view syntax, we could also have used Cython’s special NumPy array syntax, but the view syntax is preferred.
The two-dimensional example we created using Fortran is just as easy to write in Cython:
This 2-d averaging filter runs quickly because the loop is in C and the pointer computations are done only as needed. If the code above is compiled as a module image, then a 2-d image, img, can be filtered using this code very quickly using:
Regarding the code, two things are of note: firstly, it is impossible to return a memory view to Python. Instead, a NumPy array out is first created, and then a view b onto this array is used for the computation. Secondly, the view b is typed double[:, ::1]. This means 2-d array with contiguous rows, i.e., C matrix order. Specifying the order explicitly can speed up some algorithms since they can skip stride computations.
Cython is the extension mechanism of choice for several scientific Python libraries, including Scipy, Pandas, SAGE, scikit-image and scikit-learn, as well as the XML processing library LXML. The language and compiler are well-maintained.
There are several disadvantages of using Cython:
One big advantage of Cython-generated extension modules is that they are easy to distribute. In summary, Cython is a very capable tool for either gluing C code or generating an extension module quickly and should not be over-looked. It is especially useful for people that can’t or won’t write C or Fortran code.
Ctypes is a Python extension module, included in the stdlib, that allows you to call an arbitrary function in a shared library directly from Python. This approach allows you to interface with C-code directly from Python. This opens up an enormous number of libraries for use from Python. The drawback, however, is that coding mistakes can lead to ugly program crashes very easily (just as can happen in C) because there is little type or bounds checking done on the parameters. This is especially true when array data is passed in as a pointer to a raw memory location. The responsibility is then on you that the subroutine will not access memory outside the actual array area. But, if you don’t mind living a little dangerously ctypes can be an effective tool for quickly taking advantage of a large shared library (or writing extended functionality in your own shared library).
Because the ctypes approach exposes a raw interface to the compiled code it is not always tolerant of user mistakes. Robust use of the ctypes module typically involves an additional layer of Python code in order to check the data types and array bounds of objects passed to the underlying subroutine. This additional layer of checking (not to mention the conversion from ctypes objects to C-data-types that ctypes itself performs), will make the interface slower than a hand-written extension-module interface. However, this overhead should be negligible if the C-routine being called is doing any significant amount of work. If you are a great Python programmer with weak C skills, ctypes is an easy way to write a useful interface to a (shared) library of compiled code.
To use ctypes you must
There are several requirements for a shared library that can be used with ctypes that are platform specific. This guide assumes you have some familiarity with making a shared library on your system (or simply have a shared library available to you). Items to remember are:
On some platforms (e.g. Windows), a shared library requires a .def file that specifies the functions to be exported. For example a mylib.def file might contain:
Alternatively, you may be able to use the storage-class specifier __declspec(dllexport) in the C-definition of the function to avoid the need for this .def file.
There is no standard way in Python distutils to create a standard shared library (an extension module is a “special” shared library Python understands) in a cross-platform manner. Thus, a big disadvantage of ctypes at the time of writing this book is that it is difficult to distribute in a cross-platform manner a Python extension that uses ctypes and includes your own code which should be compiled as a shared library on the users system.
A simple, but robust way to load the shared library is to get the absolute path name and load it using the cdll object of ctypes:
However, on Windows accessing an attribute of the cdll method will load the first DLL by that name found in the current directory or on the PATH. Loading the absolute path name requires a little finesse for cross-platform work since the extension of shared libraries varies. There is a ctypes.util.find_library utility available that can simplify the process of finding the library to load but it is not foolproof. Complicating matters, different platforms have different default extensions used by shared libraries (e.g. .dll – Windows, .so – Linux, .dylib – Mac OS X). This must also be taken into account if you are using ctypes to wrap code that needs to work on several platforms.
NumPy provides a convenience function called ctypeslib.load_library (name, path). This function takes the name of the shared library (including any prefix like ‘lib’ but excluding the extension) and a path where the shared library can be located. It returns a ctypes library object or raises an OSError if the library cannot be found or raises an ImportError if the ctypes module is not available. (Windows users: the ctypes library object loaded using load_library is always loaded assuming cdecl calling convention. See the ctypes documentation under ctypes.windll and/or ctypes.oledll for ways to load libraries under other calling conventions).
The functions in the shared library are available as attributes of the ctypes library object (returned from ctypeslib.load_library) or as items using lib['func_name'] syntax. The latter method for retrieving a function name is particularly useful if the function name contains characters that are not allowable in Python variable names.
Python ints/longs, strings, and unicode objects are automatically converted as needed to equivalent ctypes arguments The None object is also converted automatically to a NULL pointer. All other Python objects must be converted to ctypes-specific types. There are two ways around this restriction that allow ctypes to integrate with other objects.
NumPy uses both methods with a preference for the second method because it can be safer. The ctypes attribute of the ndarray returns an object that has an _as_parameter_ attribute which returns an integer representing the address of the ndarray to which it is associated. As a result, one can pass this ctypes attribute object directly to a function expecting a pointer to the data in your ndarray. The caller must be sure that the ndarray object is of the correct type, shape, and has the correct flags set or risk nasty crashes if the data-pointer to inappropriate arrays are passed in.
To implement the second method, NumPy provides the class-factory function ndpointer in the numpy.ctypeslib module. This class-factory function produces an appropriate class that can be placed in an argtypes attribute entry of a ctypes function. The class will contain a from_param method which ctypes will use to convert any ndarray passed in to the function to a ctypes-recognized object. In the process, the conversion will perform checking on any properties of the ndarray that were specified by the user in the call to ndpointer. Aspects of the ndarray that can be checked include the data-type, the number-of-dimensions, the shape, and/or the state of the flags on any array passed. The return value of the from_param method is the ctypes attribute of the array which (because it contains the _as_parameter_ attribute pointing to the array data area) can be used by ctypes directly.
The ctypes attribute of an ndarray is also endowed with additional attributes that may be convenient when passing additional information about the array into a ctypes function. The attributes data, shape, and strides can provide ctypes compatible types corresponding to the data-area, the shape, and the strides of the array. The data attribute returns a c_void_p representing a pointer to the data area. The shape and strides attributes each return an array of ctypes integers (or None representing a NULL pointer, if a 0-d array). The base ctype of the array is a ctype integer of the same size as a pointer on the platform. There are also methods data_as({ctype}), shape_as(<base ctype>), and strides_as(<base
ctype>). These return the data as a ctype object of your choice and the shape/strides arrays using an underlying base type of your choice. For convenience, the ctypeslib module also contains c_intp as a ctypes integer data-type whose size is the same as the size of c_void_p on the platform (its value is None if ctypes is not installed).
The function is accessed as an attribute of or an item from the loaded shared-library. Thus, if ./mylib.so has a function named cool_function1, it may be accessed either as:
In ctypes, the return-value of a function is set to be ‘int’ by default. This behavior can be changed by setting the restype attribute of the function. Use None for the restype if the function has no return value (‘void’):
As previously discussed, you can also set the argtypes attribute of the function in order to have ctypes check the types of the input arguments when the function is called. Use the ndpointer factory function to generate a ready-made class for data-type, shape, and flags checking on your new function. The ndpointer function has the signature
Keyword arguments with the value None are not checked. Specifying a keyword enforces checking of that aspect of the ndarray on conversion to a ctypes-compatible object. The dtype keyword can be any object understood as a data-type object. The ndim keyword should be an integer, and the shape keyword should be an integer or a sequence of integers. The flags keyword specifies the minimal flags that are required on any array passed in. This can be specified as a string of comma separated requirements, an integer indicating the requirement bits OR’d together, or a flags object returned from the flags attribute of an array with the necessary requirements.
Using an ndpointer class in the argtypes method can make it significantly safer to call a C function using ctypes and the data- area of an ndarray. You may still want to wrap the function in an additional Python wrapper to make it user-friendly (hiding some obvious arguments and making some arguments output arguments). In this process, the requires function in NumPy may be useful to return the right kind of array from a given input.
In this example, we will demonstrate how the addition function and the filter function implemented previously using the other approaches can be implemented using ctypes. First, the C code which implements the algorithms contains the functions zadd, dadd, sadd, cadd, and dfilter2d. The zadd function is:
with similar code for cadd, dadd, and sadd that handles complex float, double, and float data-types, respectively:
The code.c file also contains the function dfilter2d:
A possible advantage this code has over the Fortran-equivalent code is that it takes arbitrarily strided (i.e. non-contiguous arrays) and may also run faster depending on the optimization capability of your compiler. But, it is an obviously more complicated than the simple code in filter.f. This code must be compiled into a shared library. On my Linux system this is accomplished using:
Which creates a shared_library named code.so in the current directory. On Windows don’t forget to either add __declspec(dllexport) in front of void on the line preceding each function definition, or write a code.def file that lists the names of the functions to be exported.
A suitable Python interface to this shared library should be constructed. To do this create a file named interface.py with the following lines at the top:
This code loads the shared library named code.{ext} located in the same path as this file. It then adds a return type of void to the functions contained in the library. It also adds argument checking to the functions in the library so that ndarrays can be passed as the first three arguments along with an integer (large enough to hold a pointer on the platform) as the fourth argument.
Setting up the filtering function is similar and allows the filtering function to be called with ndarray arguments as the first two arguments and with pointers to integers (large enough to handle the strides and shape of an ndarray) as the last two arguments.:
Next, define a simple selection function that chooses which addition function to call in the shared library based on the data-type:
Finally, the two functions to be exported by the interface can be written simply as:
and:
Using ctypes is a powerful way to connect Python with arbitrary C-code. Its advantages for extending Python include
clean separation of C code from Python code
Its disadvantages include
Because of the difficulty in distributing an extension module made using ctypes, f2py and Cython are still the easiest ways to extend Python for package creation. However, ctypes is in some cases a useful alternative. This should bring more features to ctypes that should eliminate the difficulty in extending Python and distributing the extension using ctypes.
These tools have been found useful by others using Python and so are included here. They are discussed separately because they are either older ways to do things now handled by f2py, Cython, or ctypes (SWIG, PyFort) or because of a lack of reasonable documentation (SIP, Boost). Links to these methods are not included since the most relevant can be found using Google or some other search engine, and any links provided here would be quickly dated. Do not assume that inclusion in this list means that the package deserves attention. Information about these packages are collected here because many people have found them useful and we’d like to give you as many options as possible for tackling the problem of easily integrating your code.
Simplified Wrapper and Interface Generator (SWIG) is an old and fairly stable method for wrapping C/C++-libraries to a large variety of other languages. It does not specifically understand NumPy arrays but can be made usable with NumPy through the use of typemaps. There are some sample typemaps in the numpy/tools/swig directory under numpy.i together with an example module that makes use of them. SWIG excels at wrapping large C/C++ libraries because it can (almost) parse their headers and auto-produce an interface. Technically, you need to generate a .i file that defines the interface. Often, however, this .i file can be parts of the header itself. The interface usually needs a bit of tweaking to be very useful. This ability to parse C/C++ headers and auto-generate the interface still makes SWIG a useful approach to adding functionalilty from C/C++ into Python, despite the other methods that have emerged that are more targeted to Python. SWIG can actually target extensions for several languages, but the typemaps usually have to be language-specific. Nonetheless, with modifications to the Python-specific typemaps, SWIG can be used to interface a library with other languages such as Perl, Tcl, and Ruby.
My experience with SWIG has been generally positive in that it is relatively easy to use and quite powerful. It has been used often before becoming more proficient at writing C-extensions. However, writing custom interfaces with SWIG is often troublesome because it must be done using the concept of typemaps which are not Python specific and are written in a C-like syntax. Therefore, other gluing strategies are preferred and SWIG would be probably considered only to wrap a very-large C/C++ library. Nonetheless, there are others who use SWIG quite happily.
SIP is another tool for wrapping C/C++ libraries that is Python specific and appears to have very good support for C++. Riverbank Computing developed SIP in order to create Python bindings to the QT library. An interface file must be written to generate the binding, but the interface file looks a lot like a C/C++ header file. While SIP is not a full C++ parser, it understands quite a bit of C++ syntax as well as its own special directives that allow modification of how the Python binding is accomplished. It also allows the user to define mappings between Python types and C/C++ structures and classes.
Boost is a repository of C++ libraries and Boost.Python is one of those libraries which provides a concise interface for binding C++ classes and functions to Python. The amazing part of the Boost.Python approach is that it works entirely in pure C++ without introducing a new syntax. Many users of C++ report that Boost.Python makes it possible to combine the best of both worlds in a seamless fashion. Using Boost to wrap simple C-subroutines is usually over-kill. Its primary purpose is to make C++ classes available in Python. So, if you have a set of C++ classes that need to be integrated cleanly into Python, consider learning about and using Boost.Python.
PyFort is a nice tool for wrapping Fortran and Fortran-like C-code into Python with support for Numeric arrays. It was written by Paul Dubois, a distinguished computer scientist and the very first maintainer of Numeric (now retired). It is worth mentioning in the hopes that somebody will update PyFort to work with NumPy arrays as well which now support either Fortran or C-style contiguous arrays.


method
Return a parametrized wrapper around the number type.
New in version 1.22.
A parametrized number type.
See also
Type hinting generics in standard collections.
This method is only available for python 3.9 and later.


Calculate the absolute value element-wise.
np.abs is a shorthand for this function.
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
An ndarray containing the absolute value of each element in x. For complex input, a + ib, the absolute value is \(\sqrt{ a^2 + b^2 }\). This is a scalar if x is a scalar.
Plot the function over [-10, 10]:
Plot the function over the complex plane:
The abs function can be used as a shorthand for np.absolute on ndarrays.


Add arguments element-wise.
The arrays to be added. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.
Equivalent to x1 + x2 in terms of array broadcasting.
The + operator can be used as a shorthand for np.add on ndarrays.


Test whether all array elements along a given axis evaluate to True.
Input array or object that can be converted to an array.
Axis or axes along which a logical AND reduction is performed. The default (axis=None) is to perform a logical AND over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.
New in version 1.7.0.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.
Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved (e.g., if dtype(out) is float, the result will consist of 0.0’s and 1.0’s). See Output type determination for more details.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the all method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
Elements to include in checking for all True values. See reduce for details.
New in version 1.20.0.
A new boolean or array is returned unless out is specified, in which case a reference to out is returned.
See also
equivalent method
Test whether any element along a given axis evaluates to True.
Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.


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.
Input arrays to compare.
The relative tolerance parameter (see Notes).
The absolute tolerance parameter (see Notes).
Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array.
New in version 1.10.0.
Returns True if the two arrays are equal within the given tolerance; False otherwise.
See also
If the following equation is element-wise True, then allclose returns True.
absolute(a - b) <= (atol + rtol * absolute(b))
The above equation is not symmetric in a and b, so that allclose(a, b) might be different from allclose(b, a) in some rare cases.
The comparison of a and b uses standard broadcasting, which means that a and b need not have the same shape in order for allclose(a, b) to evaluate to True. The same is true for equal but not array_equal.
allclose is not defined for non-numeric data types. bool is considered a numeric data-type for this purpose.


Return the maximum of an array or maximum along an axis.
Input data.
Axis or axes along which to operate. By default, flattened input is used.
New in version 1.7.0.
If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before.
Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See Output type determination for more details.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the amax method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
The minimum value of an output element. Must be present to allow computation on empty slice. See reduce for details.
New in version 1.15.0.
Elements to compare for the maximum. See reduce for details.
New in version 1.17.0.
Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.
See also
The minimum value of an array along a given axis, propagating any NaNs.
The maximum value of an array along a given axis, ignoring any NaNs.
Element-wise maximum of two arrays, propagating any NaNs.
Element-wise maximum of two arrays, ignoring any NaNs.
Return the indices of the maximum values.
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).
You can use an initial value to compute the maximum of an empty slice, or to initialize it to a different value:
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.


Return the minimum of an array or minimum along an axis.
Input data.
Axis or axes along which to operate. By default, flattened input is used.
New in version 1.7.0.
If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before.
Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See Output type determination for more details.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the amin method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
The maximum value of an output element. Must be present to allow computation on empty slice. See reduce for details.
New in version 1.15.0.
Elements to compare for the minimum. See reduce for details.
New in version 1.17.0.
Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.
See also
The maximum value of an array along a given axis, propagating any NaNs.
The minimum value of an array along a given axis, ignoring any NaNs.
Element-wise minimum of two arrays, propagating any NaNs.
Element-wise minimum of two arrays, ignoring any NaNs.
Return the indices of the minimum values.
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).
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.


Return the angle of the complex argument.
A complex number or sequence of complex numbers.
Return angle in degrees if True, radians if False (default).
The counterclockwise angle from the positive real axis on the complex plane in the range (-pi, pi], with dtype as numpy.float64.
Changed in version 1.16.0: This function works on subclasses of ndarray like ma.array.
See also
Although the angle of the complex number 0 is undefined, numpy.angle(0) returns the value 0.


Test whether any array element along a given axis evaluates to True.
Returns single boolean unless axis is not None
Input array or object that can be converted to an array.
Axis or axes along which a logical OR reduction is performed. The default (axis=None) is to perform a logical OR over all the dimensions of the input array. axis may be negative, in which case it counts from the last to the first axis.
New in version 1.7.0.
If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.
Alternate output array in which to place the result. It must have the same shape as the expected output and its type is preserved (e.g., if it is of type float, then it will remain so, returning 1.0 for True and 0.0 for False, regardless of the type of a). See Output type determination for more details.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the any method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
Elements to include in checking for any True values. See reduce for details.
New in version 1.20.0.
A new boolean or ndarray is returned unless out is specified, in which case a reference to out is returned.
See also
equivalent method
Test whether all elements along a given axis evaluate to True.
Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.


Append values to the end of an array.
Values are appended to a copy of this array.
These values are appended to a copy of arr. It must be of the correct shape (the same shape as arr, excluding axis). If axis is not specified, values can be any shape and will be flattened before use.
The axis along which values are appended. If axis is not given, both arr and values are flattened before use.
A copy of arr with values appended to axis. Note that append does not occur in-place: a new array is allocated and filled. If axis is None, out is a flattened array.
See also
Insert elements into an array.
Delete elements from an array.
When axis is specified, values must have the correct shape.


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:
Equivalently, eliminating the inner loop, this can be expressed as:
This function should accept 1-D arrays. It is applied to 1-D slices of arr along the specified axis.
Axis along which arr is sliced.
Input array.
Additional arguments to func1d.
Additional named arguments to func1d.
New in version 1.9.0.
The output array. The shape of out is identical to the shape of arr, except along the axis dimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of func1d. So if func1d returns a scalar out will have one fewer dimensions than arr.
See also
Apply a function repeatedly over multiple axes.
For a function that returns a 1D array, the number of dimensions in outarr is the same as arr.
For a function that returns a higher dimensional array, those dimensions are inserted in place of the axis dimension.


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.
This function must take two arguments, func(a, axis).
Input array.
Axes over which func is applied; the elements must be integers.
The output array. The number of dimensions is the same as a, but the shape can be different. This depends on whether func changes the shape of its output with respect to its input.
See also
Apply a function to 1-D slices of an array along the given axis.
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.
Sum over axes 0 and 2. The result has same number of dimensions as the original array:
Tuple axis arguments to ufuncs are equivalent:


Return evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.
When using a non-integer step, such as 0.1, it is often better to use numpy.linspace. See the warnings section below for more information.
Start of interval. The interval includes this value. The default start value is 0.
End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.
Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given.
The type of the output array. If dtype is not given, infer the data type from the other input arguments.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
Array of evenly spaced values.
For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.
Warning
The length of the output might not be numerically stable.
Another stability issue is due to the internal implementation of numpy.arange. The actual step value used to populate the array is dtype(start + step) - dtype(start) and not step. Precision loss can occur here, due to casting or due to using floating points when start is much larger than step. This can lead to unexpected behaviour. For example:
In such cases, the use of numpy.linspace should be preferred.
See also
Evenly spaced numbers with careful handling of endpoints.
Arrays of evenly spaced numbers in N-dimensions.
Grid-shaped arrays of evenly spaced numbers in N-dimensions.


Trigonometric inverse cosine, element-wise.
The inverse of cos so that, if y = cos(x), then x = arccos(y).
x-coordinate on the unit circle. For real arguments, the domain is [-1, 1].
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar.
See also
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.
M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 79. https://personal.math.ubc.ca/~cbm/aands/page_79.htm
We expect the arccos of 1 to be 0, and of -1 to be pi:
Plot arccos:


Inverse hyperbolic cosine, element-wise.
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Array of the same shape as x. This is a scalar if x is a scalar.
See also
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.
M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 86. https://personal.math.ubc.ca/~cbm/aands/page_86.htm
Wikipedia, “Inverse hyperbolic function”, https://en.wikipedia.org/wiki/Arccosh


Inverse sine, element-wise.
y-coordinate on the unit circle.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar.
See also
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}.
Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79ff. https://personal.math.ubc.ca/~cbm/aands/page_79.htm


Inverse hyperbolic sine element-wise.
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Array of the same shape as x. This is a scalar if x is a scalar.
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.
M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 86. https://personal.math.ubc.ca/~cbm/aands/page_86.htm
Wikipedia, “Inverse hyperbolic function”, https://en.wikipedia.org/wiki/Arcsinh


Trigonometric inverse tangent, element-wise.
The inverse of tan, so that if y = tan(x) then x = arctan(y).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Out has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar.
See also
The “four quadrant” arctan of the angle formed by (x, y) and the positive x-axis.
Argument of complex values.
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}.
Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79. https://personal.math.ubc.ca/~cbm/aands/page_79.htm
We expect the arctan of 0 to be 0, and of 1 to be pi/4:
Plot arctan:


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.
y-coordinates.
x-coordinates. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.
See also
arctan2 is identical to the atan2 function of the underlying C library. The following special values are defined in the C standard: [1]
x1
x2
arctan2(x1,x2)
+/- 0
+0
+/- 0
+/- 0
-0
+/- pi
> 0
+/-inf
+0 / +pi
< 0
+/-inf
-0 / -pi
+/-inf
+inf
+/- (pi/4)
+/-inf
-inf
+/- (3*pi/4)
Note that +0 and -0 are distinct floating point numbers, as are +inf and -inf.
ISO/IEC standard 9899:1999, “Programming language C.”
Consider four points in different quadrants:
Note the order of the parameters. arctan2 is defined also when x2 = 0 and at several other special points, obtaining values in the range [-pi, pi]:


Inverse hyperbolic tangent element-wise.
Input array.
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Array of the same shape as x. This is a scalar if x is a scalar.
See also
arctanh is a multivalued function: for each x there are infinitely many numbers z such that tanh(z) = x. The convention is to return the z whose imaginary part lies in [-pi/2, pi/2].
For real-valued input data types, arctanh always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, arctanh is a complex analytical function that has branch cuts [-1, -inf] and [1, inf] and is continuous from above on the former and from below on the latter.
The inverse hyperbolic tangent is also known as atanh or tanh^-1.
M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 86. https://personal.math.ubc.ca/~cbm/aands/page_86.htm
Wikipedia, “Inverse hyperbolic function”, https://en.wikipedia.org/wiki/Arctanh


Returns the indices of the maximum values along an axis.
Input array.
By default, the index is into the flattened array, otherwise along the specified axis.
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.
New in version 1.22.0.
Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. If keepdims is set to True, then the size of axis will be 1 with the resulting array having same shape as a.shape.
See also
The maximum value along a given axis.
Convert a flat index into an index tuple.
Apply np.expand_dims(index_array, axis) from argmax to an array as if by calling max.
In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.
Indexes of the maximal elements of a N-dimensional array:
Setting keepdims to True,


Returns the indices of the minimum values along an axis.
Input array.
By default, the index is into the flattened array, otherwise along the specified axis.
If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the array.
New in version 1.22.0.
Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed. If keepdims is set to True, then the size of axis will be 1 with the resulting array having same shape as a.shape.
See also
The minimum value along a given axis.
Convert a flat index into an index tuple.
Apply np.expand_dims(index_array, axis) from argmin to an array as if by calling min.
In case of multiple occurrences of the minimum values, the indices corresponding to the first occurrence are returned.
Indices of the minimum elements of a N-dimensional array:
Setting keepdims to True,


Perform an indirect partition along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as a that index data along the given axis in partitioned order.
New in version 1.8.0.
Array to sort.
Element index to partition by. The k-th element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all of them into their sorted position at once.
Deprecated since version 1.22.0: Passing booleans as index is deprecated.
Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.
Selection algorithm. Default is ‘introselect’
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
Array of indices that partition a along the specified axis. If a is one-dimensional, a[index_array] yields a partitioned a. More generally, np.take_along_axis(a, index_array, axis=a) always yields the partitioned a, irrespective of dimensionality.
See also
Describes partition algorithms used.
Inplace partition.
Full indirect sort.
Apply index_array from argpartition to an array as if by calling partition.
See partition for notes on the different selection algorithms.
One dimensional array:
Multi-dimensional array:


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.
Array to sort.
Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility.
Changed in version 1.15.0.: The ‘stable’ option was added.
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
Array of indices that sort a along the specified axis. If a is one-dimensional, a[index_array] yields a sorted a. More generally, np.take_along_axis(a, index_array, axis=axis) always yields the sorted a, irrespective of dimensionality.
See also
Describes sorting algorithms used.
Indirect stable sort with multiple keys.
Inplace sort.
Indirect partial sort.
Apply index_array from argsort to an array as if by calling sort.
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.
One dimensional array:
Two-dimensional array:
Indices of the sorted elements of a N-dimensional array:
Sorting with keys:


Find the indices of array elements that are non-zero, grouped by element.
Input data.
Indices of elements that are non-zero. Indices are grouped by element. This array will have shape (N, a.ndim) where N is the number of non-zero items.
See also
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.


Evenly round to the given number of decimals.
Input data.
Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.
Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. See Output type determination for more details.
An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned.
The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.
See also
equivalent method
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:
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:
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:
“Lecture Notes on the Status of IEEE 754”, William Kahan, https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF


Create an array.
An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. If object is a scalar, a 0-dimensional array containing object is returned.
The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence.
If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).
Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds.
order
no copy
copy=True
‘K’
unchanged
F & C order preserved, otherwise most similar order
‘A’
unchanged
F order if input is F and not C, otherwise C order
‘C’
C order
C order
‘F’
F order
F order
When copy=False and a copy is made for other reasons, the result is the same as if copy=True, with some exceptions for ‘A’, see the Notes section. The default order is ‘K’.
If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).
Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
An array object satisfying the specified requirements.
See also
Return an empty array with shape and type of input.
Return an array of ones with shape and type of input.
Return an array of zeros with shape and type of input.
Return a new array with shape of input filled with value.
Return a new uninitialized array.
Return a new array setting values to one.
Return a new array setting values to zero.
Return a new array of given shape filled with value.
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.
Upcasting:
More than one dimension:
Minimum dimensions 2:
Type provided:
Data-type consisting of more than one element:
Creating an array from sub-classes:


Return a string representation of an array.
Input array.
Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth'].
Floating point precision. Defaults to numpy.get_printoptions()['precision'].
Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress'].
Inserted between elements.
The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as:
The output is left-padded by the length of the prefix string, and wrapping is forced at the column max_line_width - len(suffix). It should be noted that the content of prefix and suffix strings are not included in the output.
Has no effect, do not use.
Deprecated since version 1.14.0.
If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:
Other keys that can be used to set a group of types at once are:
Total number of array elements which trigger summarization rather than full repr. Defaults to numpy.get_printoptions()['threshold'].
Number of array items in summary at beginning and end of each dimension. Defaults to numpy.get_printoptions()['edgeitems'].
Controls printing of the sign of floating-point types. If ‘+’, always print the sign of positive values. If ‘ ‘, always prints a space (whitespace character) in the sign position of positive values. If ‘-’, omit the sign character of positive values. Defaults to numpy.get_printoptions()['sign'].
Controls the interpretation of the precision option for floating-point types. Defaults to numpy.get_printoptions()['floatmode']. Can take the following values:
If set to the string ‘1.13’ enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to False, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility.
New in version 1.14.0.
String representation of the array.
if a callable in formatter does not return a string.
See also
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.


True if two arrays have the same shape and elements, False otherwise.
Input arrays.
Whether to compare NaN’s as equal. If the dtype of a1 and a2 is complex, values will be considered equal if either the real or the imaginary component of a given value is nan.
New in version 1.19.0.
Returns True if the arrays are equal.
See also
Returns True if two arrays are element-wise equal within a tolerance.
Returns True if input arrays are shape consistent and all elements equal.
When equal_nan is True, complex values with nan components are considered equal if either the real or the imaginary components are nan.


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.
Input arrays.
True if equivalent, False otherwise.
Showing the shape equivalence:


Return the string representation of an array.
Input array.
Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth'].
Floating point precision. Defaults to numpy.get_printoptions()['precision'].
Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress'].
The string representation of an array.
See also


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


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.
Input array.
Inserts newlines if text is longer than max_line_width. Defaults to numpy.get_printoptions()['linewidth'].
Floating point precision. Defaults to numpy.get_printoptions()['precision'].
Represent numbers “very close” to zero as zero; default is False. Very close is defined by precision: if the precision is 8, e.g., numbers smaller (in absolute value) than 5e-9 are represented as zero. Defaults to numpy.get_printoptions()['suppress'].
See also


Convert the input to an ndarray, but pass ndarray subclasses through.
Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.
By default, the data-type is inferred from the input data.
Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘C’.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
Array interpretation of a. If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.
See also
Similar function which always returns ndarrays.
Convert input to a contiguous array.
Convert input to a floating point ndarray.
Convert input to an ndarray with column-major memory order.
Similar function which checks input for NaNs and Infs.
Create an array from an iterator.
Construct an array by executing a function on grid positions.
Convert a list into an array:
Instances of ndarray subclasses are passed through as-is:


Convert the input to an array.
Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
By default, the data-type is inferred from the input data.
Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘K’.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.
See also
Similar function which passes through subclasses.
Convert input to a contiguous array.
Convert input to a floating point ndarray.
Convert input to an ndarray with column-major memory order.
Similar function which checks input for NaNs and Infs.
Create an array from an iterator.
Construct an array by executing a function on grid positions.
Convert a list into an array:
Existing arrays are not copied:
If dtype is set, array is copied only if dtype does not match:
Contrary to asanyarray, ndarray subclasses are not passed through:


Convert the input to an array, checking for NaNs or Infs.
Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Success requires no NaNs or Infs.
By default, the data-type is inferred from the input data.
Memory layout. ‘A’ and ‘K’ depend on the order of input array a. ‘C’ row-major (C-style), ‘F’ column-major (Fortran-style) memory representation. ‘A’ (any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise ‘K’ (keep) preserve input order Defaults to ‘C’.
Array interpretation of a. No copy is performed if the input is already an ndarray. If a is a subclass of ndarray, a base class ndarray is returned.
Raises ValueError if a contains NaN (Not a Number) or Inf (Infinity).
See also
Create and array.
Similar function which passes through subclasses.
Convert input to a contiguous array.
Convert input to a floating point ndarray.
Convert input to an ndarray with column-major memory order.
Create an array from an iterator.
Construct an array by executing a function on grid positions.
Convert a list into an array. If all elements are finite asarray_chkfinite is identical to asarray.
Raises ValueError if array_like contains Nans or Infs.


Return a contiguous array (ndim >= 1) in memory (C order).
Input array.
Data-type of returned array.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
Contiguous array of same shape and content as a, with type dtype if specified.
See also
Convert input to an ndarray with column-major memory order.
Return an ndarray that satisfies requirements.
Information about the memory layout of the array.
Note: This function returns an array with at least one-dimension (1-d) so it will not preserve 0-d arrays.


Return an array converted to a float type.
The input array.
Float type code to coerce input array a. If dtype is one of the ‘int’ dtypes, it is replaced with float64.
The input a as a float ndarray.


Return an array (ndim >= 1) laid out in Fortran order in memory.
Input array.
By default, the data-type is inferred from the input data.
Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.
New in version 1.20.0.
The input a in Fortran, or column-major, order.
See also
Convert input to a contiguous (C order) array.
Convert input to an ndarray with either row or column-major memory order.
Return an ndarray that satisfies requirements.
Information about the memory layout of the array.
Note: This function returns an array with at least one-dimension (1-d) so it will not preserve 0-d arrays.


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).
Input data.
Data-type of the output matrix.
data interpreted as a matrix.


Convert an array of size 1 to its scalar equivalent.
Deprecated since version 1.16: Deprecated, use numpy.ndarray.item() instead.
Input array of size 1.
Scalar representation of a. The output data type is the same type returned by the input’s item method.


Convert inputs to arrays with at least one dimension.
Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
One or more input arrays.
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.
See also


View inputs as arrays with at least two dimensions.
One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.
See also


View inputs as arrays with at least three dimensions.
One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).
See also


Compute the weighted average along the specified axis.
Array containing data to be averaged. If a is not an array, a conversion is attempted.
Axis or axes along which to average a. The default, axis=None, will average over all of the elements of the input array. If axis is negative it counts from the last to the first axis.
New in version 1.7.0.
If axis is a tuple of ints, averaging is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
An array of weights associated with the values in a. Each value in a contributes to the average according to its associated weight. The weights array can either be 1-D (in which case its length must be the size of a along the given axis) or of the same shape as a. If weights=None, then all data in a are assumed to have a weight equal to one. The 1-D calculation is:
The only constraint on weights is that sum(weights) must not be 0.
Default is False. If True, the tuple (average, sum_of_weights) is returned, otherwise only the average is returned. If weights=None, sum_of_weights is equivalent to the number of elements over which the average is taken.
Return the average along the specified axis. When returned is True, return a tuple with the average as the first element and the sum of the weights as the second element. sum_of_weights is of the same type as retval. The result dtype follows a genereal pattern. If weights is None, the result dtype will be that of a , or float64 if a is integral. Otherwise, if weights is not None and a is non- integral, the result type will be the type of lowest precision capable of representing values of both a and weights. If a happens to be integral, the previous rules still applies but the result dtype will at least be float64.
When all weights along axis are zero. See numpy.ma.average for a version robust to this type of error.
When the length of 1D weights is not the same as the shape of a along axis.
See also
average for masked arrays – useful if your data contains “missing” values
Returns the type that results from applying the numpy type promotion rules to the arguments.


Axis supplied was invalid.
This is raised whenever an axis parameter is specified that is larger than the number of array dimensions. For compatibility with code written against older numpy versions, which raised a mixture of ValueError and IndexError for this situation, this exception subclasses both to ensure that except ValueError and except IndexError statements continue to catch AxisError.
New in version 1.13.
The out of bounds axis or a custom exception message. If an axis is provided, then ndim should be specified as well.
The number of array dimensions.
A prefix for the exception message.
Negative axes are preserved:
The class constructor generally takes the axis and arrays’ dimensionality as arguments:
Alternatively, a custom exception message can be passed:
The out of bounds axis or None if a custom exception message was provided. This should be the axis as passed by the user, before any normalization to resolve negative indices.
New in version 1.22.
The number of array dimensions or None if a custom exception message was provided.
New in version 1.22.


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.
Number of points in the output window. If zero or less, an empty array is returned.
The triangular window, with the maximum value normalized to one (the value one appears only if the number of samples is odd), with the first and last samples equal to zero.
See also
The Bartlett window is defined as
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.
M.S. Bartlett, “Periodogram Analysis and Continuous Spectra”, Biometrika 37, 1-16, 1950.
E.R. Kanasewich, “Time Sequence Analysis in Geophysics”, The University of Alberta Press, 1975, pp. 109-110.
A.V. Oppenheim and R.W. Schafer, “Discrete-Time Signal Processing”, Prentice-Hall, 1999, pp. 468-471.
Wikipedia, “Window function”, https://en.wikipedia.org/wiki/Window_function
W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, “Numerical Recipes”, Cambridge University Press, 1986, page 429.
Plot the window and its frequency response (requires SciPy and matplotlib):


Return a string representation of a number in the given base system.
The value to convert. Positive and negative values are handled.
Convert number to the base number system. The valid range is 2-36, the default value is 2.
Number of zeros padded on the left. Default is 0 (no padding).
String representation of number in base system.
See also
Faster version of base_repr for base 2.


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\).
Only an integer decimal number can be used.
The length of the returned string if num is positive, or the length of the two’s complement if num is negative, provided that width is at least a sufficient number of bits for num to be represented in the designated form.
If the width value is insufficient, it will be ignored, and num will be returned in binary (num > 0) or two’s complement (num < 0) form with its width equal to the minimum number of bits needed to represent the number in the designated form. This behavior is deprecated and will later raise an error.
Deprecated since version 1.12.0.
Binary representation of num or two’s complement of num.
See also
Return a string representation of a number in the given base system.
Python’s built-in binary representation generator of an integer.
binary_repr is equivalent to using base_repr with base 2, but about 25x faster.
Wikipedia, “Two’s complement”, https://en.wikipedia.org/wiki/Two’s_complement
The two’s complement is returned when the input number is negative and width is specified:


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.
Input array.
Weights, array of the same shape as x.
A minimum number of bins for the output array.
New in version 1.6.0.
The result of binning the input array. The length of out is equal to np.amax(x)+1.
If the input is not 1-dimensional, or contains elements with negative values, or if minlength is negative.
If the type of the input is float or complex.
See also
The input array needs to be of integer dtype, otherwise a TypeError is raised:
A possible use of bincount is to perform sums over variable-size chunks of an array, using the weights keyword.


Compute the bit-wise AND of two arrays element-wise.
Computes the bit-wise AND of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator &.
Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Result. This is a scalar if both x1 and x2 are scalars.
See also
Return the binary representation of the input number as a string.
The number 13 is represented by 00001101. Likewise, 17 is represented by 00010001. The bit-wise AND of 13 and 17 is therefore 000000001, or 1:
The & operator can be used as a shorthand for np.bitwise_and on ndarrays.


Compute the bit-wise OR of two arrays element-wise.
Computes the bit-wise OR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator |.
Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Result. This is a scalar if both x1 and x2 are scalars.
See also
Return the binary representation of the input number as a string.
The number 13 has the binary representation 00001101. Likewise, 16 is represented by 00010000. The bit-wise OR of 13 and 16 is then 000111011, or 29:
The | operator can be used as a shorthand for np.bitwise_or on ndarrays.


Compute the bit-wise XOR of two arrays element-wise.
Computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ^.
Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs.
Result. This is a scalar if both x1 and x2 are scalars.
See also
Return the binary representation of the input number as a string.
The number 13 is represented by 00001101. Likewise, 17 is represented by 00010001. The bit-wise XOR of 13 and 17 is therefore 00011100, or 28:
The ^ operator can be used as a shorthand for np.bitwise_xor on ndarrays.


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.
Number of points in the output window. If zero or less, an empty array is returned.
The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).
See also
The Blackman window is defined as
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.
Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York.
Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
Plot the window and the frequency response: