Skip to content

Module unitexpr.qarray

Numpy array with the additional attribute unit.

None

View Source
"""

Numpy array with the additional attribute `unit`.

"""

from __future__ import annotations

from typing import Callable, Union

import numpy as np

from numpy.core._exceptions import UFuncTypeError

from .errors import OperationNotSupported

from .unit import UnitBase, UnitExprBase

class qarray(np.ndarray):

    """

    An array with elements representing the magnitudes of quantity that can be

    described by a numerical value and a unit.

    `qarray` is a sub-class of ndarray with the additional instance

    attributes `unit` and `info`.

    Implementation closely follows:

    https://numpy.org/devdocs/user/basics.subclassing.html#basics-subclassing

    """

    __unit_types = (UnitBase, UnitExprBase)

    __slots__ = ("__unit", "__info")

    def __new__(

        subtype,

        shape,

        dtype=float,

        buffer=None,

        offset=0,

        strides=None,

        order=None,

        unit=1.0,

        info="",

    ):

        # The call in the next line triggers a call to

        # qarray.__array_finalize__

        obj = super().__new__(

            subtype, shape, dtype, buffer, offset, strides, order

        )

        obj.unit = unit

        obj.__info = info

        return obj

    def __array_finalize__(self, obj):

        # ``self`` is a new object resulting from

        # ndarray.__new__(qarray, ...), therefore it only has

        # attributes that the ndarray.__new__ constructor gave it -

        # i.e. those of a standard ndarray.

        #

        # We could have got to the ndarray.__new__ call in 3 ways:

        # From an explicit constructor - e.g. qarray():

        #    obj is None

        #    (we're in the middle of the qarray.__new__

        #    constructor, and self.unit will be set when we return to

        #    qarray.__new__)

        if obj is None:

            return

        # From view casting - e.g arr.view(qarray):

        #    obj is arr

        #    (type(obj) can be qarray)

        # From new-from-template - e.g infoarr[:3]

        #    type(obj) is qarray

        #

        # Note that it is here, rather than in the __new__ method,

        # that we set the default value for 'unit', because this

        # method sees all creation of default objects - with the

        # qarray.__new__ constructor, but also with

        # arr.view(qarray).

        self.__unit = getattr(obj, "unit", 1.0)

    @classmethod

    def from_input(cls, input, unit=1.0, info="") -> qarray:

        """Constructs a `qarray` from an existing ndarray

        or from a (nested) sequence of entries.

        """

        obj = np.asarray(input).view(cls)

        obj.unit = unit

        obj.info = info

        return obj

    @property

    def unit(self):

        """Returns the unit of the object."""

        return self.__unit

    @unit.setter

    def unit(self, value) -> None:

        factor = (

            value.factor

            if isinstance(value, self.__unit_types)

            else float(value)

        )

        if factor == 1.0:

            self.__unit = value

            return None

        if factor == 0.0:

            raise ValueError(

                f"Could not set unit with zero magnitude: {value}."

            )

        try:

            self *= factor

            self.__unit = value / factor

        except UFuncTypeError:

            cfactor = self.dtype.type(factor)

            if cfactor == factor:

                self *= cfactor

                self.__unit = value / factor

            else:

                # If factor can not be safely converted to dtype do not

                # normalize unit:

                self.__unit = value

    @property

    def info(self):

        try:

            return self.__info

        except AttributeError:

            return ""

    @info.setter

    def info(self, value: str) -> None:

        self.__info = value

    @property

    def base(self):

        """

        Returns the quantity in terms of base units.

        Note: Returns `self` if the quantity has `unit == 1.0`.

        """

        if self.unit == 1.0:

            return self

        other = self.copy()

        other.unit = self.unit.base_expr

        return other

    def __format__(self, __format_spec: str) -> str:

        if self.ndim == 0:

            return self.__str__()

        return super().__format__(__format_spec)

    def __str__(self) -> str:

        if self.ndim == 0:

            unit = f" {self.unit}" if (self.unit != 1.0) else ""

            return super().__str__() + unit

        else:

            unit = f" unit: {self.unit}" if (self.unit != 1.0) else ""

            return super().__str__() + unit

    def __repr__(self) -> str:

        unit = f", unit={self.unit}" if self.unit != 1.0 else ""

        info = f", info={self.info.__repr__()}" if self.info != "" else ""

        return super().__repr__()[:-1] + unit + info + ")"

    def __add__(self, other) -> qarray:

        if isinstance(other, self.__unit_types):

            beta = other.scaling_factor(self.unit)

            if beta is None:

                raise OperationNotSupported(self, other, "+")

            return super().__add__(1.0 / beta)

        other_unit = getattr(other, "unit", 1.0)

        # If units match simply add arrays.

        if self.unit == other_unit:

            return super().__add__(other)

        alpha = other_unit / self.unit

        if isinstance(alpha, float):

            return super().__add__(other * alpha)

        if (

            isinstance(alpha, UnitExprBase)

            and alpha.base_exponents == alpha.base_exponents_zero

        ):

            return super().__add__(other * alpha.base_factor)

        raise OperationNotSupported(self, other, "+")

    def __radd__(self, other) -> qarray:

        return self.__add__(other)

    def __sub__(self, other) -> qarray:

        if isinstance(other, self.__unit_types):

            beta = other.scaling_factor(self.unit)

            if beta is None:

                raise OperationNotSupported(self, other, "+")

            return super().__sub__(1.0 / beta)

        other_unit = getattr(other, "unit", 1.0)

        # If units match simply subtract arrays.

        if self.unit == other_unit:

            return super().__sub__(other)

        alpha = other_unit / self.unit

        if isinstance(alpha, float):

            return super().__sub__(other * alpha)

        if (

            isinstance(alpha, UnitExprBase)

            and alpha.base_exponents == alpha.base_exponents_zero

        ):

            return super().__sub__(other * alpha.base_factor)

        raise OperationNotSupported(self, other, "-")

    def __mul__(self, other) -> qarray:

        """

        Returns the result of multiplying the united ndarray `self`

        with `other`.

        """

        if isinstance(other, self.__unit_types):

            obj = self.copy()

            obj.unit = self.unit * other

            return obj

        obj = super().__mul__(other)

        other_unit = getattr(other, "unit", 1.0)

        obj.unit = self.unit * other_unit

        return obj

    def __rmul__(self, other) -> qarray:

        """

        Returns the result of multiplying `other` with the united array

        `self`.

        """

        if isinstance(other, self.__unit_types):

            obj = self.copy()

            obj.unit = other * self.unit

            return obj

        obj = super().__rmul__(other)

        other_unit = getattr(other, "unit", 1.0)

        obj.unit = other_unit * self.unit

        return obj

    def __truediv__(self, other) -> qarray:

        """

        Returns the result of dividing the united ndarray `self`

        with `other`.

        """

        if isinstance(other, self.__unit_types):

            obj = self.copy()

            obj.unit = self.unit / other

            return obj

        obj = super().__truediv__(other)

        other_unit = getattr(other, "unit", 1.0)

        obj.unit = self.unit / other_unit

        return obj

    def __rtruediv__(self, other) -> qarray:

        """

        Returns the result of dividing `other` by the united ndarray `self`.

        """

        if isinstance(other, self.__unit_types):

            obj = super().__rtruediv__(other.factor)

            obj.unit = other / self.unit

            return obj

        obj = super().__rtruediv__(other)

        other_unit = getattr(other, "unit", 1.0)

        obj.unit = other_unit / self.unit

        return obj

    def __pow__(self, other: Union[float, int]) -> qarray:

        obj = super().__pow__(other)

        obj.unit = self.unit.__pow__(other)

        return obj

    def __abs__(self) -> qarray:

        obj = super().__abs__()

        obj.unit = self.unit

        return obj

    def __neg__(self) -> qarray:

        obj = super().__neg__()

        obj.unit = self.unit

        return obj

    def __pos__(self) -> qarray:

        obj = super().__pos__()

        obj.unit = self.unit.__pos__()

        return obj

    def __eq__(self, other) -> qarray:

        result = self.compare(other, super().__eq__)

        if result is None:

            result = super().__eq__(other)

            result.unit = 1.0

            result.fill(False)

        return result

    def __le__(self, other) -> qarray:

        result = self.compare(other, super().__le__)

        if result is None:

            raise OperationNotSupported(self, other, "<=")

        return result

    def __ge__(self, other) -> qarray:

        result = self.compare(other, super().__ge__)

        if result is None:

            raise OperationNotSupported(self, other, ">=")

        return result

    def __gt__(self, other) -> qarray:

        result = self.compare(other, super().__gt__)

        if result is None:

            raise OperationNotSupported(self, other, ">")

        return result

    def __lt__(self, other) -> qarray:

        result = self.compare(other, super().__lt__)

        if result is None:

            raise OperationNotSupported(self, other, "<")

        return result

    def compare(

        self, other, comparison_operator: Callable

    ) -> Union[qarray, None]:

        """

        Generic comparison function that handles input of type `Number`,

        `ndarray` and `qarray` using `comparison_operator`.

        Returns `None` if the comparison failed due to incompatible units.

        """

        if isinstance(other, self.__unit_types):

            beta = other.scaling_factor(self.unit)

            if beta is None:

                return None

            obj = comparison_operator(1.0 / beta)

            obj.unit = 1.0

            return obj

        other_unit = getattr(other, "unit", 1.0)

        if self.unit == other_unit:

            obj = comparison_operator(other)

            obj.unit = 1.0

            return obj

        alpha = other_unit / self.unit

        if isinstance(alpha, float):

            obj = comparison_operator(other * alpha)

            obj.unit = 1.0

            return obj

        if (

            isinstance(alpha, UnitExprBase)

            and alpha.base_exponents == alpha.base_exponents_zero

        ):

            obj = comparison_operator(other * alpha.base_factor)

            obj.unit = 1.0

            return obj

        return None

Classes

qarray

class qarray(
    /,
    *args,
    **kwargs
)
View Source
class qarray(np.ndarray):

    """

    An array with elements representing the magnitudes of quantity that can be

    described by a numerical value and a unit.

    `qarray` is a sub-class of ndarray with the additional instance

    attributes `unit` and `info`.

    Implementation closely follows:

    https://numpy.org/devdocs/user/basics.subclassing.html#basics-subclassing

    """

    __unit_types = (UnitBase, UnitExprBase)

    __slots__ = ("__unit", "__info")

    def __new__(

        subtype,

        shape,

        dtype=float,

        buffer=None,

        offset=0,

        strides=None,

        order=None,

        unit=1.0,

        info="",

    ):

        # The call in the next line triggers a call to

        # qarray.__array_finalize__

        obj = super().__new__(

            subtype, shape, dtype, buffer, offset, strides, order

        )

        obj.unit = unit

        obj.__info = info

        return obj

    def __array_finalize__(self, obj):

        # ``self`` is a new object resulting from

        # ndarray.__new__(qarray, ...), therefore it only has

        # attributes that the ndarray.__new__ constructor gave it -

        # i.e. those of a standard ndarray.

        #

        # We could have got to the ndarray.__new__ call in 3 ways:

        # From an explicit constructor - e.g. qarray():

        #    obj is None

        #    (we're in the middle of the qarray.__new__

        #    constructor, and self.unit will be set when we return to

        #    qarray.__new__)

        if obj is None:

            return

        # From view casting - e.g arr.view(qarray):

        #    obj is arr

        #    (type(obj) can be qarray)

        # From new-from-template - e.g infoarr[:3]

        #    type(obj) is qarray

        #

        # Note that it is here, rather than in the __new__ method,

        # that we set the default value for 'unit', because this

        # method sees all creation of default objects - with the

        # qarray.__new__ constructor, but also with

        # arr.view(qarray).

        self.__unit = getattr(obj, "unit", 1.0)

    @classmethod

    def from_input(cls, input, unit=1.0, info="") -> qarray:

        """Constructs a `qarray` from an existing ndarray

        or from a (nested) sequence of entries.

        """

        obj = np.asarray(input).view(cls)

        obj.unit = unit

        obj.info = info

        return obj

    @property

    def unit(self):

        """Returns the unit of the object."""

        return self.__unit

    @unit.setter

    def unit(self, value) -> None:

        factor = (

            value.factor

            if isinstance(value, self.__unit_types)

            else float(value)

        )

        if factor == 1.0:

            self.__unit = value

            return None

        if factor == 0.0:

            raise ValueError(

                f"Could not set unit with zero magnitude: {value}."

            )

        try:

            self *= factor

            self.__unit = value / factor

        except UFuncTypeError:

            cfactor = self.dtype.type(factor)

            if cfactor == factor:

                self *= cfactor

                self.__unit = value / factor

            else:

                # If factor can not be safely converted to dtype do not

                # normalize unit:

                self.__unit = value

    @property

    def info(self):

        try:

            return self.__info

        except AttributeError:

            return ""

    @info.setter

    def info(self, value: str) -> None:

        self.__info = value

    @property

    def base(self):

        """

        Returns the quantity in terms of base units.

        Note: Returns `self` if the quantity has `unit == 1.0`.

        """

        if self.unit == 1.0:

            return self

        other = self.copy()

        other.unit = self.unit.base_expr

        return other

    def __format__(self, __format_spec: str) -> str:

        if self.ndim == 0:

            return self.__str__()

        return super().__format__(__format_spec)

    def __str__(self) -> str:

        if self.ndim == 0:

            unit = f" {self.unit}" if (self.unit != 1.0) else ""

            return super().__str__() + unit

        else:

            unit = f" unit: {self.unit}" if (self.unit != 1.0) else ""

            return super().__str__() + unit

    def __repr__(self) -> str:

        unit = f", unit={self.unit}" if self.unit != 1.0 else ""

        info = f", info={self.info.__repr__()}" if self.info != "" else ""

        return super().__repr__()[:-1] + unit + info + ")"

    def __add__(self, other) -> qarray:

        if isinstance(other, self.__unit_types):

            beta = other.scaling_factor(self.unit)

            if beta is None:

                raise OperationNotSupported(self, other, "+")

            return super().__add__(1.0 / beta)

        other_unit = getattr(other, "unit", 1.0)

        # If units match simply add arrays.

        if self.unit == other_unit:

            return super().__add__(other)

        alpha = other_unit / self.unit

        if isinstance(alpha, float):

            return super().__add__(other * alpha)

        if (

            isinstance(alpha, UnitExprBase)

            and alpha.base_exponents == alpha.base_exponents_zero

        ):

            return super().__add__(other * alpha.base_factor)

        raise OperationNotSupported(self, other, "+")

    def __radd__(self, other) -> qarray:

        return self.__add__(other)

    def __sub__(self, other) -> qarray:

        if isinstance(other, self.__unit_types):

            beta = other.scaling_factor(self.unit)

            if beta is None:

                raise OperationNotSupported(self, other, "+")

            return super().__sub__(1.0 / beta)

        other_unit = getattr(other, "unit", 1.0)

        # If units match simply subtract arrays.

        if self.unit == other_unit:

            return super().__sub__(other)

        alpha = other_unit / self.unit

        if isinstance(alpha, float):

            return super().__sub__(other * alpha)

        if (

            isinstance(alpha, UnitExprBase)

            and alpha.base_exponents == alpha.base_exponents_zero

        ):

            return super().__sub__(other * alpha.base_factor)

        raise OperationNotSupported(self, other, "-")

    def __mul__(self, other) -> qarray:

        """

        Returns the result of multiplying the united ndarray `self`

        with `other`.

        """

        if isinstance(other, self.__unit_types):

            obj = self.copy()

            obj.unit = self.unit * other

            return obj

        obj = super().__mul__(other)

        other_unit = getattr(other, "unit", 1.0)

        obj.unit = self.unit * other_unit

        return obj

    def __rmul__(self, other) -> qarray:

        """

        Returns the result of multiplying `other` with the united array

        `self`.

        """

        if isinstance(other, self.__unit_types):

            obj = self.copy()

            obj.unit = other * self.unit

            return obj

        obj = super().__rmul__(other)

        other_unit = getattr(other, "unit", 1.0)

        obj.unit = other_unit * self.unit

        return obj

    def __truediv__(self, other) -> qarray:

        """

        Returns the result of dividing the united ndarray `self`

        with `other`.

        """

        if isinstance(other, self.__unit_types):

            obj = self.copy()

            obj.unit = self.unit / other

            return obj

        obj = super().__truediv__(other)

        other_unit = getattr(other, "unit", 1.0)

        obj.unit = self.unit / other_unit

        return obj

    def __rtruediv__(self, other) -> qarray:

        """

        Returns the result of dividing `other` by the united ndarray `self`.

        """

        if isinstance(other, self.__unit_types):

            obj = super().__rtruediv__(other.factor)

            obj.unit = other / self.unit

            return obj

        obj = super().__rtruediv__(other)

        other_unit = getattr(other, "unit", 1.0)

        obj.unit = other_unit / self.unit

        return obj

    def __pow__(self, other: Union[float, int]) -> qarray:

        obj = super().__pow__(other)

        obj.unit = self.unit.__pow__(other)

        return obj

    def __abs__(self) -> qarray:

        obj = super().__abs__()

        obj.unit = self.unit

        return obj

    def __neg__(self) -> qarray:

        obj = super().__neg__()

        obj.unit = self.unit

        return obj

    def __pos__(self) -> qarray:

        obj = super().__pos__()

        obj.unit = self.unit.__pos__()

        return obj

    def __eq__(self, other) -> qarray:

        result = self.compare(other, super().__eq__)

        if result is None:

            result = super().__eq__(other)

            result.unit = 1.0

            result.fill(False)

        return result

    def __le__(self, other) -> qarray:

        result = self.compare(other, super().__le__)

        if result is None:

            raise OperationNotSupported(self, other, "<=")

        return result

    def __ge__(self, other) -> qarray:

        result = self.compare(other, super().__ge__)

        if result is None:

            raise OperationNotSupported(self, other, ">=")

        return result

    def __gt__(self, other) -> qarray:

        result = self.compare(other, super().__gt__)

        if result is None:

            raise OperationNotSupported(self, other, ">")

        return result

    def __lt__(self, other) -> qarray:

        result = self.compare(other, super().__lt__)

        if result is None:

            raise OperationNotSupported(self, other, "<")

        return result

    def compare(

        self, other, comparison_operator: Callable

    ) -> Union[qarray, None]:

        """

        Generic comparison function that handles input of type `Number`,

        `ndarray` and `qarray` using `comparison_operator`.

        Returns `None` if the comparison failed due to incompatible units.

        """

        if isinstance(other, self.__unit_types):

            beta = other.scaling_factor(self.unit)

            if beta is None:

                return None

            obj = comparison_operator(1.0 / beta)

            obj.unit = 1.0

            return obj

        other_unit = getattr(other, "unit", 1.0)

        if self.unit == other_unit:

            obj = comparison_operator(other)

            obj.unit = 1.0

            return obj

        alpha = other_unit / self.unit

        if isinstance(alpha, float):

            obj = comparison_operator(other * alpha)

            obj.unit = 1.0

            return obj

        if (

            isinstance(alpha, UnitExprBase)

            and alpha.base_exponents == alpha.base_exponents_zero

        ):

            obj = comparison_operator(other * alpha.base_factor)

            obj.unit = 1.0

            return obj

        return None

Ancestors (in MRO)

  • numpy.ndarray

Class variables

T
ctypes
data
dtype
flags
flat
imag
itemsize
nbytes
ndim
real
shape
size
strides

Static methods

from_input

def from_input(
    input,
    unit=1.0,
    info=''
) -> 'qarray'

Constructs a qarray from an existing ndarray

or from a (nested) sequence of entries.

View Source
    @classmethod

    def from_input(cls, input, unit=1.0, info="") -> qarray:

        """Constructs a `qarray` from an existing ndarray

        or from a (nested) sequence of entries.

        """

        obj = np.asarray(input).view(cls)

        obj.unit = unit

        obj.info = info

        return obj

Instance variables

base

Returns the quantity in terms of base units.

Note: Returns self if the quantity has unit == 1.0.

info
unit

Returns the unit of the object.

Methods

all

def all(
    ...
)

a.all(axis=None, out=None, keepdims=False, *, where=True)

Returns True if all elements evaluate to True.

Refer to numpy.all for full documentation.

any

def any(
    ...
)

a.any(axis=None, out=None, keepdims=False, *, where=True)

Returns True if any of the elements of a evaluate to True.

Refer to numpy.any for full documentation.

argmax

def argmax(
    ...
)

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

Return indices of the maximum values along the given axis.

Refer to numpy.argmax for full documentation.

argmin

def argmin(
    ...
)

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

Return indices of the minimum values along the given axis.

Refer to numpy.argmin for detailed documentation.

argpartition

def argpartition(
    ...
)

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

Returns the indices that would partition this array.

Refer to numpy.argpartition for full documentation.

.. versionadded:: 1.8.0

argsort

def argsort(
    ...
)

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

Returns the indices that would sort this array.

Refer to numpy.argsort for full documentation.

astype

def astype(
    ...
)

a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)

Copy of the array, cast to a specified type.

Parameters:

Name Type Description Default
dtype str or dtype Typecode or data-type to which the array is cast. None
order {'C', 'F', 'A', 'K'} 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'. is
casting {'no', 'equiv', 'safe', 'same_kind', 'unsafe'} Controls what kind of data casting may occur. Defaults to 'unsafe'
for backwards compatibility.
  • 'no' means the data types should not be cast at all.
  • 'equiv' means only byte-order changes are allowed.
  • 'safe' means only casts which can preserve values are allowed.
  • 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed.
  • 'unsafe' means any data conversions may be done. | s | | subok | bool | If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array. | None | | copy | bool | 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. | None |

Returns:

Type Description
ndarray Unless copy is False and the other conditions for returning the input
array are satisfied (see description for copy input parameter), arr_t
is a new array of the same shape as the input array, with dtype, order
given by dtype, order.

Raises:

Type Description
ComplexWarning When casting from complex to float or int. To avoid this,
one should use a.real.astype(t).

byteswap

def byteswap(
    ...
)

a.byteswap(inplace=False)

Swap the bytes of the array elements

Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.

Parameters:

Name Type Description Default
inplace bool If True, swap bytes in-place, default is False. is

Returns:

Type Description
ndarray The byteswapped array. If inplace is True, this is
a view to self.

choose

def choose(
    ...
)

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

Use an index array to construct a new array from a set of choices.

Refer to numpy.choose for full documentation.

clip

def clip(
    ...
)

a.clip(min=None, max=None, out=None, **kwargs)

Return an array whose values are limited to [min, max]. One of max or min must be given.

Refer to numpy.clip for full documentation.

compare

def compare(
    self,
    other,
    comparison_operator: 'Callable'
) -> 'Union[qarray, None]'

Generic comparison function that handles input of type Number,

ndarray and qarray using comparison_operator.

Returns None if the comparison failed due to incompatible units.

View Source
    def compare(

        self, other, comparison_operator: Callable

    ) -> Union[qarray, None]:

        """

        Generic comparison function that handles input of type `Number`,

        `ndarray` and `qarray` using `comparison_operator`.

        Returns `None` if the comparison failed due to incompatible units.

        """

        if isinstance(other, self.__unit_types):

            beta = other.scaling_factor(self.unit)

            if beta is None:

                return None

            obj = comparison_operator(1.0 / beta)

            obj.unit = 1.0

            return obj

        other_unit = getattr(other, "unit", 1.0)

        if self.unit == other_unit:

            obj = comparison_operator(other)

            obj.unit = 1.0

            return obj

        alpha = other_unit / self.unit

        if isinstance(alpha, float):

            obj = comparison_operator(other * alpha)

            obj.unit = 1.0

            return obj

        if (

            isinstance(alpha, UnitExprBase)

            and alpha.base_exponents == alpha.base_exponents_zero

        ):

            obj = comparison_operator(other * alpha.base_factor)

            obj.unit = 1.0

            return obj

        return None

compress

def compress(
    ...
)

a.compress(condition, axis=None, out=None)

Return selected slices of this array along given axis.

Refer to numpy.compress for full documentation.

conj

def conj(
    ...
)

a.conj()

Complex-conjugate all elements.

Refer to numpy.conjugate for full documentation.

conjugate

def conjugate(
    ...
)

a.conjugate()

Return the complex conjugate, element-wise.

Refer to numpy.conjugate for full documentation.

copy

def copy(
    ...
)

a.copy(order='C')

Return a copy of the array.

Parameters:

Name Type Description Default
order {'C', 'F', 'A', 'K'} 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 :func:numpy.copy are very
similar but have different default values for their order=
arguments, and this function always passes sub-classes through.) values
See also None None None
-------- None None None
numpy.copy Similar function with different default behavior None None
numpy.copyto None None None

cumprod

def cumprod(
    ...
)

a.cumprod(axis=None, dtype=None, out=None)

Return the cumulative product of the elements along the given axis.

Refer to numpy.cumprod for full documentation.

cumsum

def cumsum(
    ...
)

a.cumsum(axis=None, dtype=None, out=None)

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

Refer to numpy.cumsum for full documentation.

diagonal

def diagonal(
    ...
)

a.diagonal(offset=0, axis1=0, axis2=1)

Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed.

Refer to :func:numpy.diagonal for full documentation.

dot

def dot(
    ...
)

a.dot(b, out=None)

Dot product of two arrays.

Refer to numpy.dot for full documentation.

dump

def dump(
    ...
)

a.dump(file)

Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.

Parameters:

Name Type Description Default
file str or Path A string naming the dump file.

.. versionchanged:: 1.17.0 pathlib.Path objects are now accepted. | None |

dumps

def dumps(
    ...
)

a.dumps()

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

Parameters:

Name Type Description Default
None None None None

fill

def fill(
    ...
)

a.fill(value)

Fill the array with a scalar value.

Parameters:

Name Type Description Default
value scalar All elements of a will be assigned this value. None

flatten

def flatten(
    ...
)

a.flatten(order='C')

Return a copy of the array collapsed into one dimension.

Parameters:

Name Type Description Default
order {'C', 'F', 'A', 'K'} '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'. is

Returns:

Type Description
ndarray A copy of the input array, flattened to one dimension.

getfield

def getfield(
    ...
)

a.getfield(dtype, offset=0)

Returns a field of the given array as a certain type.

A field is a view of the array data with a given data-type. The values in the view are determined by the given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.

Parameters:

Name Type Description Default
dtype str or dtype The data type of the view. The dtype size of the view can not be larger
than that of the array itself. None
offset int Number of bytes to skip before beginning the element view. None

item

def item(
    ...
)

a.item(*args)

Copy an element of an array to a standard Python scalar and return it.

Parameters:

Name Type Description Default
*args Arguments (variable number and type) * none: in this case, the method only works for arrays
with one element (a.size == 1), which element is
copied into a standard Python scalar object and returned.
  • int_type: this argument is interpreted as a flat index into the array, specifying which element to copy and return.

  • tuple of int_types: functions as does a single int_type argument, except that the argument is interpreted as an nd-index into the array. | None |

Returns:

Type Description
Standard Python scalar object A copy of the specified element of the array as a suitable
Python scalar

itemset

def itemset(
    ...
)

a.itemset(*args)

Insert scalar into an array (scalar is cast to array's dtype, if possible)

There must be at least 1 argument, and define the last argument as item. Then, a.itemset(*args) is equivalent to but faster than a[args] = item. The item should be a scalar value and args must select a single item in the array a.

Parameters:

Name Type Description Default
*args Arguments If one argument: a scalar, only used in case a is of size 1.
If two arguments: the last argument is the value to be set
and must be a scalar, the first argument specifies a single array
element location. It is either an int or a tuple. None

max

def max(
    ...
)

a.max(axis=None, out=None, keepdims=False, initial=, where=True)

Return the maximum along a given axis.

Refer to numpy.amax for full documentation.

mean

def mean(
    ...
)

a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)

Returns the average of the array elements along given axis.

Refer to numpy.mean for full documentation.

min

def min(
    ...
)

a.min(axis=None, out=None, keepdims=False, initial=, where=True)

Return the minimum along a given axis.

Refer to numpy.amin for full documentation.

newbyteorder

def newbyteorder(
    ...
)

arr.newbyteorder(new_order='S', /)

Return the array with the same data viewed with a different byte order.

Equivalent to::

arr.view(arr.dtype.newbytorder(new_order))

Changes are also made in all fields and sub-arrays of the array data type.

Parameters:

Name Type Description Default
new_order string Byte order to force; a value from the byte order specifications
below. new_order codes can be any of:
  • 'S' - swap dtype from current to opposite endian
  • {'<', 'little'} - little endian
  • {'>', 'big'} - big endian
  • '=' - native order, equivalent to sys.byteorder
  • {'|', 'I'} - ignore (no change to byte order)

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

Returns:

Type Description
array New array object with the dtype reflecting given change to the
byte order.

nonzero

def nonzero(
    ...
)

a.nonzero()

Return the indices of the elements that are non-zero.

Refer to numpy.nonzero for full documentation.

partition

def partition(
    ...
)

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

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is undefined.

.. versionadded:: 1.8.0

Parameters:

Name Type Description Default
kth int or sequence of ints Element index to partition by. The kth element value will be in its
final sorted position and all smaller elements will be moved before it
and all equal or greater elements behind it.
The order of all elements in the partitions is undefined.
If provided with a sequence of kth it will partition all elements
indexed by kth of them into their sorted position at once. None
axis int Axis along which to sort. Default is -1, which means sort along the
last axis. -1
kind {'introselect'} Selection algorithm. Default is 'introselect'. is
order str or list of str 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 to be specified,
but unspecified fields will still be used, in the order in which
they come up in the dtype, to break ties. None

prod

def prod(
    ...
)

a.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)

Return the product of the array elements over the given axis

Refer to numpy.prod for full documentation.

ptp

def ptp(
    ...
)

a.ptp(axis=None, out=None, keepdims=False)

Peak to peak (maximum - minimum) value along a given axis.

Refer to numpy.ptp for full documentation.

put

def put(
    ...
)

a.put(indices, values, mode='raise')

Set a.flat[n] = values[n] for all n in indices.

Refer to numpy.put for full documentation.

ravel

def ravel(
    ...
)

a.ravel([order])

Return a flattened array.

Refer to numpy.ravel for full documentation.

repeat

def repeat(
    ...
)

a.repeat(repeats, axis=None)

Repeat elements of an array.

Refer to numpy.repeat for full documentation.

reshape

def reshape(
    ...
)

a.reshape(shape, order='C')

Returns an array containing the same data with a new shape.

Refer to numpy.reshape for full documentation.

resize

def resize(
    ...
)

a.resize(new_shape, refcheck=True)

Change shape and size of array in-place.

Parameters:

Name Type Description Default
new_shape tuple of ints, or n ints Shape of resized array. None
refcheck bool If False, reference count will not be checked. Default is True. True.

Returns:

Type Description
None None

Raises:

Type Description
ValueError 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.
SystemError If the order keyword argument is specified. This behaviour is a
bug in NumPy.

round

def round(
    ...
)

a.round(decimals=0, out=None)

Return a with each element rounded to the given number of decimals.

Refer to numpy.around for full documentation.

searchsorted

def searchsorted(
    ...
)

a.searchsorted(v, side='left', sorter=None)

Find indices where elements of v should be inserted in a to maintain order.

For full documentation, see numpy.searchsorted

setfield

def setfield(
    ...
)

a.setfield(val, dtype, offset=0)

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.

Parameters:

Name Type Description Default
val object Value to be placed in field. None
dtype dtype object Data-type of the field in which to place val. None
offset int The number of bytes into the field at which to place val. None

Returns:

Type Description
None None

setflags

def setflags(
    ...
)

a.setflags(write=None, align=None, uic=None)

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

Parameters:

Name Type Description Default
write bool Describes whether or not a can be written to. None
align bool Describes whether or not a is aligned properly for its type. None
uic bool Describes whether or not a is a copy of another "base" array. None

sort

def sort(
    ...
)

a.sort(axis=-1, kind=None, order=None)

Sort an array in-place. Refer to numpy.sort for full documentation.

Parameters:

Name Type Description Default
axis int Axis along which to sort. Default is -1, which means sort along the
last axis. -1
kind {'quicksort', 'mergesort', 'heapsort', 'stable'} 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.

.. versionchanged:: 1.15.0 The 'stable' option was added. | is | | order | str or list of str | 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. | None |

squeeze

def squeeze(
    ...
)

a.squeeze(axis=None)

Remove axes of length one from a.

Refer to numpy.squeeze for full documentation.

std

def std(
    ...
)

a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)

Returns the standard deviation of the array elements along given axis.

Refer to numpy.std for full documentation.

sum

def sum(
    ...
)

a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)

Return the sum of the array elements over the given axis.

Refer to numpy.sum for full documentation.

swapaxes

def swapaxes(
    ...
)

a.swapaxes(axis1, axis2)

Return a view of the array with axis1 and axis2 interchanged.

Refer to numpy.swapaxes for full documentation.

take

def take(
    ...
)

a.take(indices, axis=None, out=None, mode='raise')

Return an array formed from the elements of a at the given indices.

Refer to numpy.take for full documentation.

tobytes

def tobytes(
    ...
)

a.tobytes(order='C')

Construct Python bytes containing the raw data bytes in the array.

Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter.

.. versionadded:: 1.9.0

Parameters:

Name Type Description Default
order {'C', 'F', 'A'} 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'. is

Returns:

Type Description
bytes Python bytes exhibiting a copy of a's raw data.

tofile

def tofile(
    ...
)

a.tofile(fid, sep="", format="%s")

Write array to a file as text or binary (default).

Data is always written in 'C' order, independent of the order of a. The data produced by this method can be recovered using the function fromfile().

Parameters:

Name Type Description Default
fid file or str or Path An open file object, or a string containing a filename.

.. versionchanged:: 1.17.0 pathlib.Path objects are now accepted. | None | | sep | str | Separator between array items for text output. If "" (empty), a binary file is written, equivalent to file.write(a.tobytes()). | None | | format | str | 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. | None |

tolist

def tolist(
    ...
)

a.tolist()

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 ~numpy.ndarray.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.

Parameters:

Name Type Description Default
none None None None

Returns:

Type Description
object, or list of object, or list of list of object, or ... The possibly nested list of array elements.

tostring

def tostring(
    ...
)

a.tostring(order='C')

A compatibility alias for tobytes, with exactly the same behavior.

Despite its name, it returns bytes not str\ s.

trace

def trace(
    ...
)

a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)

Return the sum along diagonals of the array.

Refer to numpy.trace for full documentation.

transpose

def transpose(
    ...
)

a.transpose(*axes)

Returns a view of the array with axes transposed.

For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).

Parameters:

Name Type Description Default
axes None, tuple of ints, or n ints * None or no argument: reverses the order of the axes.
  • tuple of ints: i in the j-th place in the tuple means a's i-th axis becomes a.transpose()'s j-th axis.

  • n ints: same as an n-tuple of the same ints (this form is intended simply as a "convenience" alternative to the tuple form) | None |

Returns:

Type Description
ndarray View of a, with axes suitably permuted.

var

def var(
    ...
)

a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)

Returns the variance of the array elements, along given axis.

Refer to numpy.var for full documentation.

view

def view(
    ...
)

a.view([dtype][, type])

New view of array with the same data.

.. note:: Passing None for dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_').

Parameters:

Name Type Description Default
dtype data-type or ndarray sub-class 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). None
type Python type Type of the returned view, e.g., ndarray or matrix. Again, omission
of the parameter results in type preservation. None