See also
numpy.broadcast
The term broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. There are, however, cases where broadcasting is a bad idea because it leads to inefficient use of memory that slows computation.
NumPy operations are usually done on pairs of arrays on an element-by-element basis. In the simplest case, the two arrays must have exactly the same shape, as in the following example:
NumPy’s broadcasting rule relaxes this constraint when the arrays’ shapes meet certain constraints. The simplest broadcasting example occurs when an array and a scalar value are combined in an operation:
The result is equivalent to the previous example where b was an array. We can think of the scalar b being stretched during the arithmetic operation into an array with the same shape as a. The new elements in b, as shown in Figure 1, are simply copies of the original scalar. The stretching analogy is only conceptual. NumPy is smart enough to use the original scalar value without actually making copies so that broadcasting operations are as memory and computationally efficient as possible.
Figure 1
In the simplest example of broadcasting, the scalar b is stretched to become an array of same shape as a so the shapes are compatible for element-by-element multiplication.
The code in the second example is more efficient than that in the first because broadcasting moves less memory around during the multiplication (b is a scalar rather than an array).
When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimensions and works its way left. Two dimensions are compatible when
If these conditions are not met, a ValueError: operands could not be broadcast together exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the size that is not 1 along each axis of the inputs.
Arrays do not need to have the same number of dimensions. For example, if you have a 256x256x3 array of RGB values, and you want to scale each color in the image by a different value, you can multiply the image by a one-dimensional array with 3 values. Lining up the sizes of the trailing axes of these arrays according to the broadcast rules, shows that they are compatible:
When either of the dimensions compared is one, the other is used. In other words, dimensions with size 1 are stretched or “copied” to match the other.
In the following example, both the A and B arrays have axes with length one that are expanded to a larger size during the broadcast operation:
A set of arrays is called “broadcastable” to the same shape if the above rules produce a valid result.
For example, if a.shape is (5,1), b.shape is (1,6), c.shape is (6,) and d.shape is () so that d is a scalar, then a, b, c, and d are all broadcastable to dimension (5,6); and
Here are some more examples:
Here are examples of shapes that do not broadcast:
An example of broadcasting when a 1-d array is added to a 2-d array:
As shown in Figure 2, b is added to each row of a. In Figure 3, an exception is raised because of the incompatible shapes.
Figure 2
A one dimensional array added to a two dimensional array results in broadcasting if number of 1-d array elements matches the number of 2-d array columns.
Figure 3
When the trailing dimensions of the arrays are unequal, broadcasting fails because it is impossible to align the values in the rows of the 1st array with the elements of the 2nd arrays for element-by-element addition.
Broadcasting provides a convenient way of taking the outer product (or any other outer operation) of two arrays. The following example shows an outer addition operation of two 1-d arrays:
Figure 4
In some cases, broadcasting stretches both arrays to form an output array larger than either of the initial arrays.
Here the newaxis index operator inserts a new axis into a, making it a two-dimensional 4x1 array. Combining the 4x1 array with b, which has shape (3,), yields a 4x3 array.
Broadcasting comes up quite often in real world problems. A typical example occurs in the vector quantization (VQ) algorithm used in information theory, classification, and other related areas. The basic operation in VQ finds the closest point in a set of points, called codes in VQ jargon, to a given point, called the observation. In the very simple, two-dimensional case shown below, the values in observation describe the weight and height of an athlete to be classified. The codes represent different classes of athletes. 1 Finding the closest point requires calculating the distance between observation and each of the codes. The shortest distance provides the best match. In this example, codes[0] is the closest class indicating that the athlete is likely a basketball player.
In this example, the observation array is stretched to match the shape of the codes array:
Figure 5
The basic operation of vector quantization calculates the distance between an object to be classified, the dark square, and multiple known codes, the gray circles. In this simple case, the codes represent individual classes. More complex cases use multiple codes per class.
Typically, a large number of observations, perhaps read from a database, are compared to a set of codes. Consider this scenario:
The three-dimensional array, diff, is a consequence of broadcasting, not a necessity for the calculation. Large data sets will generate a large intermediate array that is computationally inefficient. Instead, if each observation is calculated individually using a Python loop around the code in the two-dimensional example above, a much smaller array is used.
Broadcasting is a powerful tool for writing short and usually intuitive code that does its computations very efficiently in C. However, there are cases when broadcasting uses unnecessarily large amounts of memory for a particular algorithm. In these cases, it is better to write the algorithm’s outer loop in Python. This may also produce more readable code, as algorithms that use broadcasting tend to become more difficult to interpret as the number of dimensions in the broadcast increases.
In this example, weight has more impact on the distance calculation than height because of the larger values. In practice, it is important to normalize the height and weight, often by their standard deviation across the data set, so that both have equal influence on the distance calculation.


Polynomials in NumPy can be created, manipulated, and even fitted using the convenience classes of the numpy.polynomial package, introduced in NumPy 1.4.
Prior to NumPy 1.4, numpy.poly1d was the class of choice and it is still available in order to maintain backward compatibility. However, the newer polynomial package is more complete and its convenience classes provide a more consistent, better-behaved interface for working with polynomial expressions. Therefore numpy.polynomial is recommended for new coding.
Note
Terminology
The term polynomial module refers to the old API defined in numpy.lib.polynomial, which includes the numpy.poly1d class and the polynomial functions prefixed with poly accessible from the numpy namespace (e.g. numpy.polyadd, numpy.polyval, numpy.polyfit, etc.).
The term polynomial package refers to the new API defined in numpy.polynomial, which includes the convenience classes for the different kinds of polynomials (numpy.polynomial.Polynomial, numpy.polynomial.Chebyshev, etc.).
As noted above, the poly1d class and associated functions defined in numpy.lib.polynomial, such as numpy.polyfit and numpy.poly, are considered legacy and should not be used in new code. Since NumPy version 1.4, the numpy.polynomial package is preferred for working with polynomials.
The following table highlights some of the main differences between the legacy polynomial module and the polynomial package for common tasks. The Polynomial class is imported for brevity:
How to…
Legacy (numpy.poly1d)
numpy.polynomial
Create a polynomial object from coefficients 1
p = np.poly1d([1, 2, 3])
p = Polynomial([3, 2, 1])
Create a polynomial object from roots
r = np.poly([-1, 1]) p = np.poly1d(r)
p = Polynomial.fromroots([-1, 1])
Fit a polynomial of degree deg to data
np.polyfit(x, y, deg)
Polynomial.fit(x, y, deg)
Note the reversed ordering of the coefficients
There are significant differences between numpy.lib.polynomial and numpy.polynomial. The most significant difference is the ordering of the coefficients for the polynomial expressions. The various routines in numpy.polynomial all deal with series whose coefficients go from degree zero upward, which is the reverse order of the poly1d convention. The easy way to remember this is that indices correspond to degree, i.e., coef[i] is the coefficient of the term of degree i.
Though the difference in convention may be confusing, it is straightforward to convert from the legacy polynomial API to the new. For example, the following demonstrates how you would convert a numpy.poly1d instance representing the expression \(x^{2} + 2x + 3\) to a Polynomial instance representing the same expression:
In addition to the coef attribute, polynomials from the polynomial package also have domain and window attributes. These attributes are most relevant when fitting polynomials to data, though it should be noted that polynomials with different domain and window attributes are not considered equal, and can’t be mixed in arithmetic:
See the documentation for the convenience classes for further details on the domain and window attributes.
Another major difference between the legacy polynomial module and the polynomial package is polynomial fitting. In the old module, fitting was done via the polyfit function. In the polynomial package, the fit class method is preferred. For example, consider a simple linear fit to the following data:
With the legacy polynomial module, a linear fit (i.e. polynomial of degree 1) could be applied to these data with polyfit:
With the new polynomial API, the fit class method is preferred:
Note that the coefficients are given in the scaled domain defined by the linear mapping between the window and domain. convert can be used to get the coefficients in the unscaled data domain.
In addition to standard power series polynomials, the polynomial package provides several additional kinds of polynomials including Chebyshev, Hermite (two subtypes), Laguerre, and Legendre polynomials. Each of these has an associated convenience class available from the numpy.polynomial namespace that provides a consistent interface for working with polynomials regardless of their type.
Documentation pertaining to specific functions defined for each kind of polynomial individually can be found in the corresponding module documentation:


This module provides a number of objects (mostly functions) useful for dealing with Chebyshev series, including a Chebyshev class that encapsulates the usual arithmetic operations. (General information on how this module represents and works with such polynomials is in the docstring for its “parent” sub-package, numpy.polynomial).
Chebyshev(coef[, domain, window])
A Chebyshev series class.
chebdomain
An array object represents a multidimensional, homogeneous array of fixed-size items.
chebzero
An array object represents a multidimensional, homogeneous array of fixed-size items.
chebone
An array object represents a multidimensional, homogeneous array of fixed-size items.
chebx
An array object represents a multidimensional, homogeneous array of fixed-size items.
chebadd(c1, c2)
Add one Chebyshev series to another.
chebsub(c1, c2)
Subtract one Chebyshev series from another.
chebmulx(c)
Multiply a Chebyshev series by x.
chebmul(c1, c2)
Multiply one Chebyshev series by another.
chebdiv(c1, c2)
Divide one Chebyshev series by another.
chebpow(c, pow[, maxpower])
Raise a Chebyshev series to a power.
chebval(x, c[, tensor])
Evaluate a Chebyshev series at points x.
chebval2d(x, y, c)
Evaluate a 2-D Chebyshev series at points (x, y).
chebval3d(x, y, z, c)
Evaluate a 3-D Chebyshev series at points (x, y, z).
chebgrid2d(x, y, c)
Evaluate a 2-D Chebyshev series on the Cartesian product of x and y.
chebgrid3d(x, y, z, c)
Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.
chebder(c[, m, scl, axis])
Differentiate a Chebyshev series.
chebint(c[, m, k, lbnd, scl, axis])
Integrate a Chebyshev series.
chebfromroots(roots)
Generate a Chebyshev series with given roots.
chebroots(c)
Compute the roots of a Chebyshev series.
chebvander(x, deg)
Pseudo-Vandermonde matrix of given degree.
chebvander2d(x, y, deg)
Pseudo-Vandermonde matrix of given degrees.
chebvander3d(x, y, z, deg)
Pseudo-Vandermonde matrix of given degrees.
chebgauss(deg)
Gauss-Chebyshev quadrature.
chebweight(x)
The weight function of the Chebyshev polynomials.
chebcompanion(c)
Return the scaled companion matrix of c.
chebfit(x, y, deg[, rcond, full, w])
Least squares fit of Chebyshev series to data.
chebpts1(npts)
Chebyshev points of the first kind.
chebpts2(npts)
Chebyshev points of the second kind.
chebtrim(c[, tol])
Remove "small" "trailing" coefficients from a polynomial.
chebline(off, scl)
Chebyshev series whose graph is a straight line.
cheb2poly(c)
Convert a Chebyshev series to a polynomial.
poly2cheb(pol)
Convert a polynomial to a Chebyshev series.
chebinterpolate(func, deg[, args])
Interpolate a function at the Chebyshev points of the first kind.
numpy.polynomial
The implementations of multiplication, division, integration, and differentiation use the algebraic identities [1]:
where
These identities allow a Chebyshev series to be expressed as a finite, symmetric Laurent series. In this module, this sort of Laurent series is referred to as a “z-series.”
A. T. Benjamin, et al., “Combinatorial Trigonometry with Chebyshev Polynomials,” Journal of Statistical Planning and Inference 14, 2008 (https://web.archive.org/web/20080221202153/https://www.math.hmc.edu/~benjamin/papers/CombTrig.pdf, pg. 4)


Recursively add files under data_path to data_files list.
Recursively add files under data_path to the list of data_files to be installed (and distributed). The data_path can be either a relative path-name, or an absolute path-name, or a 2-tuple where the first argument shows where in the install directory the data directory should be installed to.
Argument can be either
Rules for installation paths:
For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat:
Will install data-files to the locations:


Add data files to configuration data_files.
Argument(s) can be either
The form of each element of the files sequence is very flexible allowing many combinations of where to get the files from the package and where they should ultimately be installed on the system. The most basic usage is for an element of the files argument sequence to be a simple filename. This will cause that file from the local path to be installed to the installation path of the self.name package (package path). The file argument can also be a relative path in which case the entire relative path will be installed into the package directory. Finally, the file can be an absolute path name in which case the file will be found at the absolute path name but installed to the package path.
This basic behavior can be augmented by passing a 2-tuple in as the file argument. The first element of the tuple should specify the relative path (under the package install directory) where the remaining sequence of files should be installed to (it has nothing to do with the file-names in the source distribution). The second element of the tuple is the sequence of files that should be installed. The files in this sequence can be filenames, relative paths, or absolute paths. For absolute paths the file will be installed in the top-level package installation directory (regardless of the first argument). Filenames and relative path names will be installed in the package install directory under the path name given as the first element of the tuple.
Rules for installation paths:
An additional feature is that the path to a data-file can actually be a function that takes no arguments and returns the actual path(s) to the data-files. This is useful when the data files are generated while building the package.
Add files to the list of data_files to be included with the package.
will install these data files to:
where <package install directory> is the package (or sub-package) directory such as ‘/usr/lib/python2.4/site-packages/mypackage’ (‘C: Python2.4 Lib site-packages mypackage’) or ‘/usr/lib/python2.4/site- packages/mypackage/mysubpackage’ (‘C: Python2.4 Lib site-packages mypackage mysubpackage’).


Add extension to configuration.
Create and add an Extension instance to the ext_modules list. This method also takes the following optional keyword arguments that are passed on to the Extension constructor.
name of the extension
list of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built.
The depends list contains paths to files or directories that the sources of the extension module depend on. If any path in the depends list is newer than the extension module, then the module will be rebuilt.
dict or list of dict of keywords to be appended to keywords.
The self.paths(…) method is applied to all lists that may contain paths.


Add installable headers to configuration.
Add the given sequence of files to the beginning of the headers list. By default, headers will be installed under <python- include>/<self.name.replace(‘.’,’/’)>/ directory. If an item of files is a tuple, then its first argument specifies the actual installation location relative to the <python-include> path.
Argument(s) can be either:


Add paths to configuration include directories.
Add the given sequence of paths to the beginning of the include_dirs list. This list will be visible to all extension modules of the current package.


Similar to add_library, but the specified library is installed.
Most C libraries used with distutils are only used to build python extensions, but libraries built through this method will be installed so that they can be reused by third-party packages.
Name of the installed library.
List of the library’s source files. See add_library for details.
Path to install the library, relative to the current sub-package.
The following keys are allowed:
See also
The best way to encode the options required to link against the specified C libraries is to use a “libname.ini” file, and use get_info to retrieve the required options (see add_npy_pkg_config for more information).


Add library to configuration.
Name of the extension.
List of the sources. The list of sources may contain functions (called source generators) which must take an extension instance and a build directory as inputs and return a source file or list of source files or None. If None is returned then no sources are generated. If the Extension instance has no sources after processing all source generators, then no extension module is built.
The following keys are allowed:


Generate and install a npy-pkg config file from a template.
The config file generated from template is installed in the given install directory, using subst_dict for variable substitution.
The path of the template, relatively to the current package path.
Where to install the npy-pkg config file, relatively to the current package path.
If given, any string of the form @key@ will be replaced by subst_dict[key] in the template file when installed. The install prefix is always available through the variable @prefix@, since the install prefix is not easy to get reliably from setup.py.
See also
This works for both standard installs and in-place builds, i.e. the @prefix@ refer to the source directory for in-place builds.
Assuming the foo.ini.in file has the following content:
The generated file will have the following content:
and will be installed as foo.ini in the ‘lib’ subpath.
When cross-compiling with numpy distutils, it might be necessary to use modified npy-pkg-config files. Using the default/generated files will link with the host libraries (i.e. libnpymath.a). For cross-compilation you of-course need to link with target libraries, while using the host Python installation.
You can copy out the numpy/core/lib/npy-pkg-config directory, add a pkgdir value to the .ini files and set NPY_PKG_CONFIG_PATH environment variable to point to the directory with the modified npy-pkg-config files.
Example npymath.ini modified for cross-compilation:


Add scripts to configuration.
Add the sequence of files to the beginning of the scripts list. Scripts will be installed under the <prefix>/bin/ directory.


Add a sub-package to the current Configuration instance.
This is useful in a setup.py script for adding sub-packages to a package.
name of the subpackage
if given, the subpackage path such as the subpackage is in subpackage_path / subpackage_name. If None,the subpackage is assumed to be located in the local path / subpackage_name.


attribute
current index in broadcasted result


attribute
tuple of iterators along self’s “components.”
Returns a tuple of numpy.flatiter objects, one for each “component” of self.
See also


attribute
Number of dimensions of broadcasted result. For code intended for NumPy 1.12.0 and later the more consistent ndim is preferred.


attribute
Number of dimensions of broadcasted result. Alias for nd.
New in version 1.12.0.


attribute
Number of iterators possessed by the broadcasted result.


method
Reset the broadcasted result’s iterator(s).


attribute
Total size of broadcasted result.


numpy.distutils is part of NumPy, and extends the standard Python distutils module to deal with Fortran sources and F2PY signature files, e.g. compile Fortran sources, call F2PY to construct extension modules, etc.
Example
Consider the following setup_file.py for the fib and scalar examples from Three ways to wrap - getting started section:
Running
will build two extension modules scalar and fib2 to the build directory.
numpy.distutils extends distutils with the following features:
Extension class argument sources may contain Fortran source files. In addition, the list sources may contain at most one F2PY signature file, and in this case, the name of an Extension module must match with the <modulename> used in signature file. It is assumed that an F2PY signature file contains exactly one python
module block.
If sources do not contain a signature file, then F2PY is used to scan Fortran source files to construct wrappers to the Fortran codes.
Additional options to the F2PY executable can be given using the Extension class argument f2py_options.
The following new distutils commands are defined:
to construct Fortran wrapper extension modules, among many other things.
to change Fortran compiler options.
Additionally, the build_ext and build_clib commands are also enhanced to support Fortran sources.
Run
to see available options for these commands.
When building Python packages containing Fortran sources, one can choose different Fortran compilers by using the build_ext command option --fcompiler=<Vendor>. Here <Vendor> can be one of the following names (on linux systems):
See numpy_distutils/fcompiler.py for an up-to-date list of supported compilers for different platforms, or run


attribute
A copy of the holiday array indicating additional invalid days.


attribute
A copy of the seven-element boolean mask indicating valid days.


The ndarray is an object that provide a python array interface to data in memory.
It often happens that the memory that you want to view with an array is not of the same byte ordering as the computer on which you are running Python.
For example, I might be working on a computer with a little-endian CPU - such as an Intel Pentium, but I have loaded some data from a file written by a computer that is big-endian. Let’s say I have loaded 4 bytes from a file written by a Sun (big-endian) computer. I know that these 4 bytes represent two 16-bit integers. On a big-endian machine, a two-byte integer is stored with the Most Significant Byte (MSB) first, and then the Least Significant Byte (LSB). Thus the bytes are, in memory order:
Let’s say the two integers were in fact 1 and 770. Because 770 = 256 * 3 + 2, the 4 bytes in memory would contain respectively: 0, 1, 3, 2. The bytes I have loaded from the file would have these contents:
We might want to use an ndarray to access these integers. In that case, we can create an array around this memory, and tell numpy that there are two integers, and that they are 16 bit and big-endian:
Note the array dtype above of >i2. The > means ‘big-endian’ (< is little-endian) and i2 means ‘signed 2-byte integer’. For example, if our data represented a single unsigned 4-byte little-endian integer, the dtype string would be <u4.
In fact, why don’t we try that?
Returning to our big_end_arr - in this case our underlying data is big-endian (data endianness) and we’ve set the dtype to match (the dtype is also big-endian). However, sometimes you need to flip these around.
Warning
Scalars currently do not include byte order information, so extracting a scalar from an array will return an integer in native byte order. Hence:
As you can imagine from the introduction, there are two ways you can affect the relationship between the byte ordering of the array and the underlying memory it is looking at:
The common situations in which you need to change byte ordering are:
We make something where they don’t match:
The obvious fix for this situation is to change the dtype so it gives the correct endianness:
Note the array has not changed in memory:
You might want to do this if you need the data in memory to be a certain ordering. For example you might be writing the memory out to a file that needs a certain byte ordering.
Now the array has changed in memory:
You may have a correctly specified array dtype, but you need the array to have the opposite byte order in memory, and you want the dtype to match so the array values make sense. In this case you just do both of the previous operations:
An easier way of casting the data to a specific dtype and byte ordering can be achieved with the ndarray astype method:


Return element-wise string concatenation for two arrays of str or unicode.
Arrays x1 and x2 must have the same shape.
Input array.
Input array.
Output array of string_ or unicode_, depending on input types of the same shape as x1 and x2.


Create a chararray.
Note
This class is provided for numarray backward-compatibility. New code (not concerned with numarray compatibility) should use arrays of type string_ or unicode_ and use the free functions in numpy.char for fast vectorized string operations instead.
Versus a regular NumPy array of type str or unicode, this class adds the following functionality:
itemsize is the number of characters per scalar in the resulting array. If itemsize is None, and obj is an object array or a Python list, the itemsize will be automatically determined. If itemsize is provided and obj is of type str or unicode, then the obj string will be chunked into itemsize pieces.
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 (itemsize, unicode, order, etc.).
When true, the resulting chararray can contain Unicode characters, when false only 8-bit characters. If unicode is None and obj is one of the following:
then the unicode setting of the output array will be automatically determined.
Specify the order of the array. If order is ‘C’ (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is ‘F’, then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is ‘A’, then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous).


Convert the input to a chararray, copying the data only if necessary.
Versus a regular NumPy array of type str or unicode, this class adds the following functionality:
itemsize is the number of characters per scalar in the resulting array. If itemsize is None, and obj is an object array or a Python list, the itemsize will be automatically determined. If itemsize is provided and obj is of type str or unicode, then the obj string will be chunked into itemsize pieces.
When true, the resulting chararray can contain Unicode characters, when false only 8-bit characters. If unicode is None and obj is one of the following:
then the unicode setting of the output array will be automatically determined.
Specify the order of the array. If order is ‘C’ (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is ‘F’, then the returned array will be in Fortran-contiguous order (first-index varies the fastest).


Return a copy of a with only the first character of each element capitalized.
Calls str.capitalize element-wise.
For 8-bit strings, this method is locale-dependent.
Input array of strings to capitalize.
Output array of str or unicode, depending on input types
See also


Return a copy of a with its elements centered in a string of length width.
Calls str.center element-wise.
The length of the resulting strings
The padding character to use (default is space).
Output array of str or unicode, depending on input types
See also


method
Returns the indices that would sort this array.
Refer to numpy.argsort for full documentation.
See also
equivalent function


method
Copy of the array, cast to a specified type.
Typecode or data-type to which the array is cast.
Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.
Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.


attribute
Base object if memory is from some other object.
The base of an array that owns its memory is None:
Slicing creates a view, whose memory is shared with x:


method
Return a copy of the array.
Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and numpy.copy are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)
See also
Similar function with different default behavior
This function is the preferred method for creating an array copy. The function numpy.copy is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.


method
Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end].
See also


attribute
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.
Possessing attributes data, shape, strides, etc.
See also
Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes, as well as documented private attributes):
A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as self._array_interface_['data'][0].
Note that unlike data_as, a reference will not be kept to the array: code like ctypes.c_void_p((a + b).ctypes.data) will result in a pointer to a deallocated array, and should be spelt (a + b).ctypes.data_as(ctypes.c_void_p)
(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform (see c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array.
(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.
Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).
The returned pointer will keep a reference to the array.
Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short).
Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong).
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as_parameter attribute which will return an integer equal to the data attribute.


attribute
Python buffer object pointing to the start of the array’s data.


method
Calls str.decode element-wise.
See also


attribute
Data-type of the array’s elements.
See also


method
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
A string naming the dump file.
Changed in version 1.17.0: pathlib.Path objects are now accepted.


method
Returns the pickle of the array as a string. pickle.loads will convert the string back to an array.


method
Calls str.encode element-wise.
See also


method
Returns a boolean array which is True where the string element in self ends with suffix, otherwise False.
See also


method
Return a copy of each string element where all tab characters are replaced by one or more spaces.
See also


method
Fill the array with a scalar value.
All elements of a will be assigned this value.


method
For each element, return the lowest index in the string where substring sub is found.
See also


attribute
Information about the memory layout of the array.
The flags object can be accessed dictionary-like (as in a.flags['WRITEABLE']), or by using lowercased attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access.
Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0] == self.itemsize for Fortran-style contiguous arrays is true.
The data is in a single, C-style contiguous segment.
The data is in a single, Fortran-style contiguous segment.
The array owns the memory it uses or borrows it from another object.
The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.
The data and all elements are aligned appropriately for the hardware.
This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.
(Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array.
F_CONTIGUOUS and not C_CONTIGUOUS.
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
ALIGNED and WRITEABLE.
BEHAVED and C_CONTIGUOUS.
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.


attribute
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.
See also
Return a copy of the array collapsed into one dimension.
An assignment example:


method
Return a copy of the array collapsed into one dimension.
‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
A copy of the input array, flattened to one dimension.
See also
Return a flattened array.
A 1-D flat iterator over the array.


method
Returns a field of the given array as a certain type.
A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.
The data type of the view. The dtype size of the view can not be larger than that of the array itself.
Number of bytes to skip before beginning the element view.
By choosing an offset of 8 bytes we can select the complex part of the array for our view:


attribute
The imaginary part of the array.


method
Like find, but raises ValueError when the substring is not found.
See also


method
Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise.
See also


method
Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise.
See also


method
For each element in self, return True if there are only decimal characters in the element.
See also


method
Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise.
See also


method
Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
See also


method
For each element in self, return True if there are only numeric characters in the element.
See also


method
Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise.
See also


method
Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise.
See also


method
Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise.
See also


method
Copy an element of an array to a standard Python scalar and return it.
A copy of the specified element of the array as a suitable Python scalar
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.


attribute
Length of one array element in bytes.


method
Return a string which is the concatenation of the strings in the sequence seq.
See also


method
Return an array with the elements of self left-justified in a string of length width.
See also


method
Return an array with the elements of self converted to lowercase.
See also


method
For each element in self, return a copy with the leading characters removed.
See also


attribute
Total bytes consumed by the elements of the array.
Does not include memory consumed by non-element attributes of the array object.


method
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See also
equivalent function


method
Set a.flat[n] = values[n] for all n in indices.
Refer to numpy.put for full documentation.
See also
equivalent function


method
Return a flattened array.
Refer to numpy.ravel for full documentation.
See also
equivalent function
a flat iterator on the array.


attribute
The real part of the array.
See also
equivalent function


method
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See also
equivalent function


method
For each element in self, return a copy of the string with all occurrences of substring old replaced by new.
See also


method
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See also
equivalent function
Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).


method
Change shape and size of array in-place.
Shape of resized array.
If False, reference count will not be checked. Default is True.
If a does not own its own data or references or views to it exist, and the data memory must be changed. PyPy only: will always raise if the data memory must be changed, since there is no reliable way to determine if references or views to it exist.
If the order keyword argument is specified. This behaviour is a bug in NumPy.
See also
Return a new array with the specified shape.
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped:
Enlarging an array: as above, but missing entries are filled with zeros:
Referencing an array prevents resizing…
Unless refcheck is False:


method
For each element in self, return the highest index in the string where substring sub is found, such that sub is contained within [start, end].
See also


method
Like rfind, but raises ValueError when the substring sub is not found.
See also


method
Return an array with the elements of self right-justified in a string of length width.
See also


method
For each element in self, return a list of the words in the string, using sep as the delimiter string.
See also


method
For each element in self, return a copy with the trailing characters removed.
See also


method
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See also
equivalent function


method
Put a value into a specified place in a field defined by a data-type.
Place val into a’s field defined by dtype and beginning offset bytes into the field.
Value to be placed in field.
Data-type of the field in which to place val.
The number of bytes into the field at which to place val.
See also


method
Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.)
Describes whether or not a can be written to.
Describes whether or not a is aligned properly for its type.
Describes whether or not a is a copy of another “base” array.
Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only four of which can be changed by the user: WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler);
UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY;
WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array.
All flags can be accessed using the single (upper case) letter as well as the full name.


attribute
Tuple of array dimensions.
The shape property is usually used to get the current shape of an array, but may also be used to reshape the array in-place by assigning a tuple of array dimensions to it. As with numpy.reshape, one of the new shape dimensions can be -1, in which case its value is inferred from the size of the array and the remaining dimensions. Reshaping an array in-place will fail if a copy is required.
See also
similar function
similar method


attribute
Number of elements in the array.
Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.
a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.


method
Sort an array in-place. Refer to numpy.sort for full documentation.
Axis along which to sort. Default is -1, which means sort along the last axis.
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. The ‘mergesort’ option is retained for backwards compatibility.
Changed in version 1.15.0: The ‘stable’ option was added.
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
See also
Return a sorted copy of an array.
Indirect sort.
Indirect stable sort on multiple keys.
Find elements in sorted array.
Partial sort.
See numpy.sort for notes on the different sorting algorithms.
Use the order keyword to specify a field to use when sorting a structured array:


method
For each element in self, return a list of the lines in the element, breaking at line boundaries.
See also


method
Remove axes of length one from a.
Refer to numpy.squeeze for full documentation.
See also
equivalent function


method
Returns a boolean array which is True where the string element in self starts with prefix, otherwise False.
See also


attribute
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:
A more detailed explanation of strides can be found in the “ndarray.rst” file in the NumPy reference guide.
See also
Imagine an array of 32-bit integers (each 4 bytes):
This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be (20, 4).


method
For each element in self, return a copy with the leading and trailing characters removed.
See also


method
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See also
equivalent function


method
For each element in self, return a copy of the string with uppercase characters converted to lowercase and vice versa.
See also


attribute
The transposed array.
Same as self.transpose().
See also


method
Return an array formed from the elements of a at the given indices.
Refer to numpy.take for full documentation.
See also
equivalent function


method
For each element in self, return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase.
See also


method
Construct Python bytes containing the raw data bytes in the array.
Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter.
New in version 1.9.0.
Controls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’.
Python bytes exhibiting a copy of a’s raw data.


method
Write array to a file as text or binary (default).
Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile().
An open file object, or a string containing a filename.
Changed in version 1.17.0: pathlib.Path objects are now accepted.
Separator between array items for text output. If “” (empty), a binary file is written, equivalent to file.write(a.tobytes()).
Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using “format” % item.
This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.
When fid is a file object, array contents are directly written to the file, bypassing the file object’s write method. As a result, tofile cannot be used with files objects supporting compression (e.g., GzipFile) or file-like objects that do not support fileno() (e.g., BytesIO).


method
Return the array as an a.ndim-levels deep nested list of Python scalars.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function.
If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar.
The possibly nested list of array elements.
The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision.
For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars:
Additionally, for a 2D array, tolist applies recursively:
The base case for this recursion is a 0D array:


method
A compatibility alias for tobytes, with exactly the same behavior.
Despite its name, it returns bytes not strs.
Deprecated since version 1.19.0.


method
For each element in self, return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table.
See also


method
Returns a view of the array with axes transposed.
For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).
View of a, with axes suitably permuted.
See also
Equivalent function
Array property returning the array transposed.
Give a new shape to an array without changing its data.


method
Return an array with the elements of self converted to uppercase.
See also


method
New view of array with the same data.
Note
Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_').
Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter).
Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.
a.view() is used two different ways:
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory.
For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results.
Viewing array data using a different type and dtype:
Creating a view on a structured array so it can be used in calculations
Making changes to the view changes the underlying array
Using a view to convert an array to a recarray:
Views share data:
Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.:


method
Return the numeric string left-filled with zeros in a string of length width.
See also


Performs element-wise comparison of two string arrays using the comparison operator specified by cmp_op.
Arrays to be compared.
Type of comparison.
If True, the spaces at the end of Strings are removed before the comparison.
The output array of type Boolean with the same shape as a and b.
If cmp_op is not valid.
If at least one of a or b is a non-string array


Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end].
Calls str.count element-wise.
The substring to search for.
Optional arguments start and end are interpreted as slice notation to specify the range in which to count.
Output array of ints.
See also


Calls str.decode element-wise.
The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the codecs module.
The name of an encoding
Specifies how to handle encoding errors
See also
The type of the result will depend on the encoding specified.


Calls str.encode element-wise.
The set of available codecs comes from the Python standard library, and may be extended at runtime. For more information, see the codecs module.
The name of an encoding
Specifies how to handle encoding errors
See also
The type of the result will depend on the encoding specified.


Returns a boolean array which is True where the string element in a ends with suffix, otherwise False.
Calls str.endswith element-wise.
With optional start, test beginning at that position. With optional end, stop comparing at that position.
Outputs an array of bools.
See also


Return (x1 == x2) element-wise.
Unlike numpy.equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.
Input arrays of the same shape.
Output array of bools.
See also


Return a copy of each string element where all tab characters are replaced by one or more spaces.
Calls str.expandtabs element-wise.
Return a copy of each string element where all tab characters are replaced by one or more spaces, depending on the current column and the given tabsize. The column number is reset to zero after each newline occurring in the string. This doesn’t understand other non-printing characters or escape sequences.
Input array
Replace tabs with tabsize number of spaces. If not given defaults to 8 spaces.
Output array of str or unicode, depending on input type
See also


For each element, return the lowest index in the string where substring sub is found.
Calls str.find element-wise.
For each element, return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end].
Optional arguments start and end are interpreted as in slice notation.
Output array of ints. Returns -1 if sub is not found.
See also


Return (x1 > x2) element-wise.
Unlike numpy.greater, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.
Input arrays of the same shape.
Output array of bools.
See also


Return (x1 >= x2) element-wise.
Unlike numpy.greater_equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.
Input arrays of the same shape.
Output array of bools.
See also


Like find, but raises ValueError when the substring is not found.
Calls str.index element-wise.
Output array of ints. Returns -1 if sub is not found.
See also


Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise.
Calls str.isalnum element-wise.
For 8-bit strings, this method is locale-dependent.
Output array of str or unicode, depending on input type
See also


Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise.
Calls str.isalpha element-wise.
For 8-bit strings, this method is locale-dependent.
Output array of bools
See also


For each element, return True if there are only decimal characters in the element.
Calls unicode.isdecimal element-wise.
Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.
Input array.
Array of booleans identical in shape to a.
See also


Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise.
Calls str.isdigit element-wise.
For 8-bit strings, this method is locale-dependent.
Output array of bools
See also


Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
Calls str.islower element-wise.
For 8-bit strings, this method is locale-dependent.
Output array of bools
See also


For each element, return True if there are only numeric characters in the element.
Calls unicode.isnumeric element-wise.
Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155,
VULGAR FRACTION ONE FIFTH.
Input array.
Array of booleans of same shape as a.
See also


Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise.
Calls str.isspace element-wise.
For 8-bit strings, this method is locale-dependent.
Output array of bools
See also


Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise.
Call str.istitle element-wise.
For 8-bit strings, this method is locale-dependent.
Output array of bools
See also


Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise.
Call str.isupper element-wise.
For 8-bit strings, this method is locale-dependent.
Output array of bools
See also


Return a string which is the concatenation of the strings in the sequence seq.
Calls str.join element-wise.
Output array of str or unicode, depending on input types
See also


Return (x1 < x2) element-wise.
Unlike numpy.greater, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.
Input arrays of the same shape.
Output array of bools.
See also


Return (x1 <= x2) element-wise.
Unlike numpy.less_equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.
Input arrays of the same shape.
Output array of bools.
See also


Return an array with the elements of a left-justified in a string of length width.
Calls str.ljust element-wise.
The length of the resulting strings
The character to use for padding
Output array of str or unicode, depending on input type
See also


Return an array with the elements converted to lowercase.
Call str.lower element-wise.
For 8-bit strings, this method is locale-dependent.
Input array.
Output array of str or unicode, depending on input type
See also


For each element in a, return a copy with the leading characters removed.
Calls str.lstrip element-wise.
Input array.
The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped.
Output array of str or unicode, depending on input type
See also
The ‘a’ variable is unstripped from c[1] because whitespace leading.


Return (a % i), that is pre-Python 2.6 string formatting (interpolation), element-wise for a pair of array_likes of str or unicode.
These values will be element-wise interpolated into the string.
Output array of str or unicode, depending on input types
See also


Return (a * i), that is string multiple concatenation, element-wise.
Values in i of less than 0 are treated as 0 (which yields an empty string).
Output array of str or unicode, depending on input types


Return (x1 != x2) element-wise.
Unlike numpy.not_equal, this comparison is performed by first stripping whitespace characters from the end of the string. This behavior is provided for backward-compatibility with numarray.
Input arrays of the same shape.
Output array of bools.
See also


Partition each element in a around sep.
Calls str.partition element-wise.
For each element in a, split the element as the first occurrence of sep, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings.
Input array
Separator to split each string element in a.
Output array of str or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element.
See also


For each element in a, return a copy of the string with all occurrences of substring old replaced by new.
Calls str.replace element-wise.
If the optional argument count is given, only the first count occurrences are replaced.
Output array of str or unicode, depending on input type
See also


For each element in a, return the highest index in the string where substring sub is found, such that sub is contained within [start, end].
Calls str.rfind element-wise.
Optional arguments start and end are interpreted as in slice notation.
Output array of ints. Return -1 on failure.
See also


Like rfind, but raises ValueError when the substring sub is not found.
Calls str.rindex element-wise.
Output array of ints.
See also


Return an array with the elements of a right-justified in a string of length width.
Calls str.rjust element-wise.
The length of the resulting strings
The character to use for padding
Output array of str or unicode, depending on input type
See also


Partition (split) each element around the right-most separator.
Calls str.rpartition element-wise.
For each element in a, split the element as the last occurrence of sep, and return 3 strings containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return 3 strings containing the string itself, followed by two empty strings.
Input array
Right-most separator to split each element in array.
Output array of string or unicode, depending on input type. The output array will have an extra dimension with 3 elements per input element.
See also


For each element in a, return a list of the words in the string, using sep as the delimiter string.
Calls str.rsplit element-wise.
Except for splitting from the right, rsplit behaves like split.
If sep is not specified or None, any whitespace string is a separator.
If maxsplit is given, at most maxsplit splits are done, the rightmost ones.
Array of list objects
See also


For each element in a, return a copy with the trailing characters removed.
Calls str.rstrip element-wise.
The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped.
Output array of str or unicode, depending on input type
See also


For each element in a, return a list of the words in the string, using sep as the delimiter string.
Calls str.split element-wise.
If sep is not specified or None, any whitespace string is a separator.
If maxsplit is given, at most maxsplit splits are done.
Array of list objects
See also


For each element in a, return a list of the lines in the element, breaking at line boundaries.
Calls str.splitlines element-wise.
Line breaks are not included in the resulting list unless keepends is given and true.
Array of list objects
See also


Returns a boolean array which is True where the string element in a starts with prefix, otherwise False.
Calls str.startswith element-wise.
With optional start, test beginning at that position. With optional end, stop comparing at that position.
Array of booleans
See also


Return len(a) element-wise.
Output array of integers
See also


For each element in a, return a copy with the leading and trailing characters removed.
Calls str.strip element-wise.
The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped.
Output array of str or unicode, depending on input type
See also


Return element-wise a copy of the string with uppercase characters converted to lowercase and vice versa.
Calls str.swapcase element-wise.
For 8-bit strings, this method is locale-dependent.
Input array.
Output array of str or unicode, depending on input type
See also


Return element-wise title cased version of string or unicode.
Title case words start with uppercase characters, all remaining cased characters are lowercase.
Calls str.title element-wise.
For 8-bit strings, this method is locale-dependent.
Input array.
Output array of str or unicode, depending on input type
See also


For each element in a, return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table.
Calls str.translate element-wise.
Output array of str or unicode, depending on input type
See also


Return an array with the elements converted to uppercase.
Calls str.upper element-wise.
For 8-bit strings, this method is locale-dependent.
Input array.
Output array of str or unicode, depending on input type
See also


Return the numeric string left-filled with zeros
Calls str.zfill element-wise.
Input array.
Width of string to left-fill elements in a.
Output array of str or unicode, depending on input type
See also


method
Returns the indices that would sort this array.
Refer to numpy.argsort for full documentation.
See also
equivalent function


method
Copy of the array, cast to a specified type.
Typecode or data-type to which the array is cast.
Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.
When casting from complex to float or int. To avoid this, one should use a.real.astype(t).
Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.
Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.


attribute
Base object if memory is from some other object.
The base of an array that owns its memory is None:
Slicing creates a view, whose memory is shared with x:


method
Return a copy of the array.
Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and numpy.copy are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)
See also
Similar function with different default behavior
This function is the preferred method for creating an array copy. The function numpy.copy is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.


method
Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end].
See also


attribute
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.
Possessing attributes data, shape, strides, etc.
See also
Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes, as well as documented private attributes):
A pointer to the memory area of the array as a Python integer. This memory area may contain data that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as self._array_interface_['data'][0].
Note that unlike data_as, a reference will not be kept to the array: code like ctypes.c_void_p((a + b).ctypes.data) will result in a pointer to a deallocated array, and should be spelt (a + b).ctypes.data_as(ctypes.c_void_p)
(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corresponding to dtype('p') on this platform (see c_intp). This base-type could be ctypes.c_int, ctypes.c_long, or ctypes.c_longlong depending on the platform. The ctypes array contains the shape of the underlying array.
(c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. This ctypes array contains the strides information from the underlying array. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.
Return the data pointer cast to a particular c-types object. For example, calling self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).
The returned pointer will keep a reference to the array.
Return the shape tuple as an array of some other c-types type. For example: self.shape_as(ctypes.c_short).
Return the strides tuple as an array of some other c-types type. For example: self.strides_as(ctypes.c_longlong).
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as_parameter attribute which will return an integer equal to the data attribute.


attribute
Python buffer object pointing to the start of the array’s data.


method
Calls str.decode element-wise.
See also


method
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
A string naming the dump file.
Changed in version 1.17.0: pathlib.Path objects are now accepted.


method
Returns the pickle of the array as a string. pickle.loads will convert the string back to an array.


method
Calls str.encode element-wise.
See also


method
Returns a boolean array which is True where the string element in self ends with suffix, otherwise False.
See also


method
Return a copy of each string element where all tab characters are replaced by one or more spaces.
See also


method
Fill the array with a scalar value.
All elements of a will be assigned this value.


method
For each element, return the lowest index in the string where substring sub is found.
See also


attribute
Information about the memory layout of the array.
The flags object can be accessed dictionary-like (as in a.flags['WRITEABLE']), or by using lowercased attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access.
Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assignment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0] == self.itemsize for Fortran-style contiguous arrays is true.
The data is in a single, C-style contiguous segment.
The data is in a single, Fortran-style contiguous segment.
The array owns the memory it uses or borrows it from another object.
The data area can be written to. Setting this to False locks the data, making it read-only. A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a view of a writeable array may be subsequently locked while the base array remains writeable. (The opposite is not true, in that a view of a locked array may not be made writeable. However, currently, locking a base object does not lock any views that already reference it, so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.) Attempting to change a non-writeable array raises a RuntimeError exception.
The data and all elements are aligned appropriately for the hardware.
This array is a copy of some other array. The C-API function PyArray_ResolveWritebackIfCopy must be called before deallocating to the base array will be updated with the contents of this array.
(Deprecated, use WRITEBACKIFCOPY) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array.
F_CONTIGUOUS and not C_CONTIGUOUS.
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
ALIGNED and WRITEABLE.
BEHAVED and C_CONTIGUOUS.
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.


attribute
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.
See also
Return a copy of the array collapsed into one dimension.
An assignment example:


method
Return a copy of the array collapsed into one dimension.
‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
A copy of the input array, flattened to one dimension.
See also
Return a flattened array.
A 1-D flat iterator over the array.


method
Returns a field of the given array as a certain type.
A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.
The data type of the view. The dtype size of the view can not be larger than that of the array itself.
Number of bytes to skip before beginning the element view.
By choosing an offset of 8 bytes we can select the complex part of the array for our view:


method
Like find, but raises ValueError when the substring is not found.
See also


method
Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise.
See also


method
Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise.
See also


method
For each element in self, return True if there are only decimal characters in the element.
See also


method
Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise.
See also


method
Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
See also


method
For each element in self, return True if there are only numeric characters in the element.
See also


method
Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise.
See also


method
Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise.
See also


method
Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise.
See also


method
Copy an element of an array to a standard Python scalar and return it.
A copy of the specified element of the array as a suitable Python scalar
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.


attribute
Length of one array element in bytes.


method
Return a string which is the concatenation of the strings in the sequence seq.
See also


method
Return an array with the elements of self left-justified in a string of length width.
See also


method
Return an array with the elements of self converted to lowercase.
See also


method
For each element in self, return a copy with the leading characters removed.
See also


attribute
Total bytes consumed by the elements of the array.
Does not include memory consumed by non-element attributes of the array object.


method
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See also
equivalent function


method
Set a.flat[n] = values[n] for all n in indices.
Refer to numpy.put for full documentation.
See also
equivalent function


method
Return a flattened array.
Refer to numpy.ravel for full documentation.
See also
equivalent function
a flat iterator on the array.


method
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See also
equivalent function


method
For each element in self, return a copy of the string with all occurrences of substring old replaced by new.
See also


method
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See also
equivalent function
Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).


method
Change shape and size of array in-place.
Shape of resized array.
If False, reference count will not be checked. Default is True.
If a does not own its own data or references or views to it exist, and the data memory must be changed. PyPy only: will always raise if the data memory must be changed, since there is no reliable way to determine if references or views to it exist.
If the order keyword argument is specified. This behaviour is a bug in NumPy.
See also
Return a new array with the specified shape.
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped:
Enlarging an array: as above, but missing entries are filled with zeros:
Referencing an array prevents resizing…
Unless refcheck is False:


method
For each element in self, return the highest index in the string where substring sub is found, such that sub is contained within [start, end].
See also


method
Like rfind, but raises ValueError when the substring sub is not found.
See also


method
Return an array with the elements of self right-justified in a string of length width.
See also


method
For each element in self, return a list of the words in the string, using sep as the delimiter string.
See also


method
For each element in self, return a copy with the trailing characters removed.
See also


method
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See also
equivalent function


method
Put a value into a specified place in a field defined by a data-type.
Place val into a’s field defined by dtype and beginning offset bytes into the field.
Value to be placed in field.
Data-type of the field in which to place val.
The number of bytes into the field at which to place val.
See also


method
Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.
These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The WRITEBACKIFCOPY and (deprecated) UPDATEIFCOPY flags can never be set to True. The flag WRITEABLE can only be set to True if the array owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a string. (The exception for string is made so that unpickling can be done without copying memory.)
Describes whether or not a can be written to.
Describes whether or not a is aligned properly for its type.
Describes whether or not a is a copy of another “base” array.
Array flags provide information about how the memory area used for the array is to be interpreted. There are 7 Boolean flags in use, only four of which can be changed by the user: WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler);
UPDATEIFCOPY (U) (deprecated), replaced by WRITEBACKIFCOPY;
WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced by .base). When the C-API function PyArray_ResolveWritebackIfCopy is called, the base array will be updated with the contents of this array.
All flags can be accessed using the single (upper case) letter as well as the full name.


attribute
Number of elements in the array.
Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.
a.size returns a standard arbitrary precision Python integer. This may not be the case with other methods of obtaining the same value (like the suggested np.prod(a.shape), which returns an instance of np.int_), and may be relevant if the value is used further in calculations that may overflow a fixed size integer type.


method
Sort an array in-place. Refer to numpy.sort for full documentation.
Axis along which to sort. Default is -1, which means sort along the last axis.
Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. The ‘mergesort’ option is retained for backwards compatibility.
Changed in version 1.15.0: The ‘stable’ option was added.
When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
See also
Return a sorted copy of an array.
Indirect sort.
Indirect stable sort on multiple keys.
Find elements in sorted array.
Partial sort.
See numpy.sort for notes on the different sorting algorithms.
Use the order keyword to specify a field to use when sorting a structured array:


method
For each element in self, return a list of the lines in the element, breaking at line boundaries.
See also


method
Remove axes of length one from a.
Refer to numpy.squeeze for full documentation.
See also
equivalent function


method
Returns a boolean array which is True where the string element in self starts with prefix, otherwise False.
See also


attribute
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:
A more detailed explanation of strides can be found in the “ndarray.rst” file in the NumPy reference guide.
See also
Imagine an array of 32-bit integers (each 4 bytes):
This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be (20, 4).


method
For each element in self, return a copy with the leading and trailing characters removed.
See also


method
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See also
equivalent function


method
For each element in self, return a copy of the string with uppercase characters converted to lowercase and vice versa.
See also


attribute
The transposed array.
Same as self.transpose().
See also


method
Return an array formed from the elements of a at the given indices.
Refer to numpy.take for full documentation.
See also
equivalent function


method
For each element in self, return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase.
See also


method
Construct Python bytes containing the raw data bytes in the array.
Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter.
New in version 1.9.0.
Controls the memory layout of the bytes object. ‘C’ means C-order, ‘F’ means F-order, ‘A’ (short for Any) means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. Default is ‘C’.
Python bytes exhibiting a copy of a’s raw data.


method
Write array to a file as text or binary (default).
Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile().
An open file object, or a string containing a filename.
Changed in version 1.17.0: pathlib.Path objects are now accepted.
Separator between array items for text output. If “” (empty), a binary file is written, equivalent to file.write(a.tobytes()).
Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using “format” % item.
This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.
When fid is a file object, array contents are directly written to the file, bypassing the file object’s write method. As a result, tofile cannot be used with files objects supporting compression (e.g., GzipFile) or file-like objects that do not support fileno() (e.g., BytesIO).


method
Return the array as an a.ndim-levels deep nested list of Python scalars.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function.
If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar.
The possibly nested list of array elements.
The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision.
For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars:
Additionally, for a 2D array, tolist applies recursively:
The base case for this recursion is a 0D array:


method
A compatibility alias for tobytes, with exactly the same behavior.
Despite its name, it returns bytes not strs.
Deprecated since version 1.19.0.


method
For each element in self, return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table.
See also


method
Returns a view of the array with axes transposed.
For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).
View of a, with axes suitably permuted.
See also
Equivalent function
Array property returning the array transposed.
Give a new shape to an array without changing its data.


method
Return an array with the elements of self converted to uppercase.
See also


method
New view of array with the same data.
Note
Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_').
Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter).
Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.
a.view() is used two different ways:
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass) or a.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory.
For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a slice or transpose, etc., the view may give different results.
Viewing array data using a different type and dtype:
Creating a view on a structured array so it can be used in calculations
Making changes to the view changes the underlying array
Using a view to convert an array to a recarray:
Views share data:
Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.:


method
Return the numeric string left-filled with zeros in a string of length width.
See also


If a class (ndarray subclass or not) having the __array__ method is used as the output object of an ufunc, results will not be written to the object returned by __array__. This practice will return TypeError.


This method is called whenever the system internally allocates a new array from obj, where obj is a subclass (subtype) of the ndarray. It can be used to change attributes of self after construction (so as to ensure a 2-d matrix for example), or to update meta-information from the “parent.” Subclasses inherit a default implementation of this method that does nothing.