NumPy docstrings#

This page demonstrates NumPy docstrings for the theme, as well as some other common Sphinx directives for API documentation.

Added in version 0.1.1.

NumPy#

Provides
  1. An array object of arbitrary homogeneous items

  2. Fast mathematical operations over arrays

  3. Linear Algebra, Fourier Transforms, Random Number Generation

How to use the documentation#

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

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

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

>>> import numpy as np

Code snippets are indicated by three greater-than signs:

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

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

>>> help(np.sort)
... 

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

To search for documents containing a keyword, do:

>>> np.lookfor('keyword')
... 

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

>>> from numpy import doc
>>> help(doc)
... 

Available subpackages#

lib

Basic functions used by several sub-packages.

random

Core Random Tools

linalg

Core Linear Algebra Tools

fft

Core FFT routines

polynomial

Polynomial tools

testing

NumPy testing tools

distutils

Enhancements to distutils with support for Fortran compilers support and more (for Python <= 3.11).

Utilities#

test

Run numpy unittests

show_config

Show numpy build configuration

matlib

Make everything matrices.

__version__

NumPy version string

Viewing documentation using IPython#

Start IPython and import numpy usually under the alias np: import numpy as np. Then, directly past or use the %cpaste magic to paste examples into the shell. To see which functions are available in numpy, type np.<TAB> (where <TAB> refers to the TAB key), or use np.*cos*?<ENTER> (where <ENTER> refers to the ENTER key) to narrow down the list. To view the docstring for a function, use np.cos?<ENTER> (to view the docstring) and np.cos??<ENTER> (to view the source code).

Copies vs. in-place operation#

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

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

Create an array.

Parameters:
objectarray_like

An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. If object is a scalar, a 0-dimensional array containing object is returned.

dtypedata-type, optional

The desired data-type for the array. If not given, NumPy will try to use a default dtype that can represent the values (by applying promotion rules when necessary.)

copybool, optional

If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

order{‘K’, ‘A’, ‘C’, ‘F’}, optional

Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds.

order

no copy

copy=True

‘K’

unchanged

F & C order preserved, otherwise most similar order

‘A’

unchanged

F order if input is F and not C, otherwise C order

‘C’

C order

C order

‘F’

F order

F order

When copy=False and a copy is made for other reasons, the result is the same as if copy=True, with some exceptions for ‘A’, see the Notes section. The default order is ‘K’.

subokbool, optional

If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).

ndminint, optional

Specifies the minimum number of dimensions that the resulting array should have. Ones will be prepended to the shape as needed to meet this requirement.

likearray_like, optional

Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument.

Added in version 1.20.0.

Returns:
outndarray

An array object satisfying the specified requirements.

See also

empty_like

Return an empty array with shape and type of input.

ones_like

Return an array of ones with shape and type of input.

zeros_like

Return an array of zeros with shape and type of input.

full_like

Return a new array with shape of input filled with value.

empty

Return a new uninitialized array.

ones

Return a new array setting values to one.

zeros

Return a new array setting values to zero.

full

Return a new array of given shape filled with value.

Notes

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

Examples

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

Upcasting:

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

More than one dimension:

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

Minimum dimensions 2:

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

Type provided:

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

Data-type consisting of more than one element:

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

Creating an array from sub-classes:

>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
       [3, 4]])
>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
        [3, 4]])
numpy.transpose(a, axes=None)#

Returns an array with axes transposed.

For a 1-D array, this returns an unchanged view of the original array, as a transposed vector is simply the same vector. To convert a 1-D array into a 2-D column vector, an additional dimension must be added, e.g., np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is the 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, then transpose(a).shape == a.shape[::-1].

Parameters:
aarray_like

Input array.

axestuple or list of ints, optional

If specified, it must be a tuple or list which contains a permutation of [0,1,…,N-1] where N is the number of axes of a. The i’th axis of the returned array will correspond to the axis numbered axes[i] of the input. If not specified, defaults to range(a.ndim)[::-1], which reverses the order of the axes.

Returns:
pndarray

a with its axes permuted. A view is returned whenever possible.

See also

ndarray.transpose

Equivalent method.

moveaxis

Move axes of an array to new positions.

argsort

Return the indices that would sort an array.

Notes

Use transpose(a, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument.

Examples

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