Skip to main content
`Ctrl`+`K`

# Quantity

class astropy.units.Quantity(value, unit=None, dtype=<class 'numpy.inexact'>, copy=True, order=None, subok=False, ndmin=0)

  Bases: `ndarray`

  A `Quantity` represents a number with some associated unit.

  See also: https://docs.astropy.org/en/stable/units/quantity.html

  Parameters:
    value number, `ndarray`, `Quantity` (python:sequence), or `python:str`

      The numerical value of this quantity in the units given by unit. If a `Quantity` or sequence of them (or any other valid object with a `unit` attribute), creates a new `Quantity` object, converting to `unit` units as needed. If a string, it is converted to a number or `Quantity`, depending on whether a unit is present.

    unit astropy:unit-like

      An object that represents the unit associated with the input value. Must be an `UnitBase` object or a string parseable by the `units` package.

    dtype `dtype`, optional

      The dtype of the resulting Numpy array or scalar that will hold the value. If not provided, it is determined from the input, except that any integer and (non-Quantity) object inputs are converted to float by default. If `None`, the normal `numpy.dtype` introspection is used, e.g. preventing upcasting of integers.

    copy bool, optional

      If `True` (default), then the value is copied. Otherwise, a copy will only be made if `__array__` returns a copy, if value is a nested sequence, or if a copy is needed to satisfy an explicitly given `dtype`. (The `False` option is intended mostly for internal use, to speed up initialization where a copy is known to have been made. Use with care.)

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

      Specify the order of the array. As in `array`. This parameter is ignored if the input is a `Quantity` and `copy=False`.

    subok bool, optional

      If `False` (default), the returned array will be forced to be a `Quantity`. Otherwise, `Quantity` subclasses will be passed through, or a subclass appropriate for the unit will be used (such as `Dex` for `u.dex(u.AA)`).

    ndmin `python:int`, 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. This parameter is ignored if the input is a `Quantity` and `copy=False`.

  Raises:
    `TypeError`

      If the value provided is not a Python numeric type.

    `TypeError`

      If the unit provided is not either a `Unit` object or a parseable string unit.

  Notes

  Quantities can also be created by multiplying a number or array with a `Unit`. See https://docs.astropy.org/en/latest/units/

  Unless the `dtype` argument is explicitly specified, integer or (non-Quantity) object inputs are converted to `float` by default.

  Attributes Summary

  `cgs` | Returns a copy of the current `Quantity` instance with CGS units.
  `equivalencies` | A list of equivalencies that will be applied by default during unit conversions.
  `flat` | A 1-D iterator over the Quantity array.
  `info` | Container for meta information like name, description, format.
  `isscalar` | True if the `value` of this quantity is a scalar, or False if it is an array-like object.
  `si` | Returns a copy of the current `Quantity` instance with SI units.
  `unit` | A `UnitBase` object representing the unit of this quantity.
  `value` | The numerical value of this instance.

  Methods Summary

  `all`([axis, out, keepdims, where]) | Returns True if all elements evaluate to True.
  `any`([axis, out, keepdims, where]) | Returns True if any of the elements of `a` evaluate to True.
  `argmax`([axis, out, keepdims]) | Return indices of the maximum values along the given axis.
  `argmin`([axis, out, keepdims]) | Return indices of the minimum values along the given axis.
  `argsort`([axis, kind, order, stable]) | Returns the indices that would sort this array.
  `choose`(choices[, out, mode]) | Use an index array to construct a new array from a set of choices.
  `decompose`([bases]) | Generates a new `Quantity` with the units decomposed.
  `diff`([n, axis]) |
  `dot`(other, /[, out]) | Refer to `numpy.dot()` for full documentation.
  `dump`(file) | Not implemented, use `.value.dump()` instead.
  `dumps`() | Not implemented, use `.value.dumps()` instead.
  `ediff1d`([to_end, to_begin]) |
  `fill`(value) | Fill the array with a scalar value.
  `insert`(obj, values[, axis]) | Insert values along the given axis before the given indices and return a new `Quantity` object.
  `item`(*args) | Copy an element of an array to a scalar Quantity and return it.
  `mean`([axis, dtype, out, keepdims, where]) | Returns the average of the array elements along given axis.
  `put`(indices, values[, mode]) | Set `a.flat[n] = values[n]` for all `n` in indices.
  `round`([decimals, out]) | Return `a` with each element rounded to the given number of decimals.
  `searchsorted`(v[, side, sorter]) | Find indices where elements of `v` should be inserted in `a` to maintain order.
  `std`([axis, dtype, out, ddof, keepdims, ...]) | Returns the standard deviation of the array elements along given axis.
  `take`(indices[, axis, out, mode]) | Return an array formed from the elements of `a` at the given indices.
  `to`(unit[, equivalencies, copy]) | Return a new `Quantity` object with the specified unit.
  `to_string`([unit, precision, format, subfmt, ...]) | Generate a string representation of the quantity and its unit.
  `to_value`([unit, equivalencies]) | The numerical value, possibly in a different unit.
  `tobytes`([order]) | Not implemented, use `.value.tobytes()` instead.
  `tofile`(fid[, sep, format]) | Not implemented, use `.value.tofile()` instead.
  `tolist`() | Return the array as an `a.ndim`-levels deep nested list of Python scalars.
  `tostring`([order]) | Not implemented, use `.value.tostring()` instead.
  `trace`([offset, axis1, axis2, dtype, out]) | Return the sum along diagonals of the array.
  `var`([axis, dtype, out, ddof, keepdims, ...]) | Returns the variance of the array elements, along given axis.

  Attributes Documentation

  cgs

    Returns a copy of the current `Quantity` instance with CGS units. The value of the resulting object will be scaled.

  equivalencies

    A list of equivalencies that will be applied by default during unit conversions.

  flat

    A 1-D iterator over the Quantity array.

    This returns a `QuantityIterator` instance, which behaves the same as the `flatiter` instance returned by `flat`, and is similar to, but not a subclass of, Python’s built-in iterator object.

  info

    Container for meta information like name, description, format. This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information.

  isscalar

    True if the `value` of this quantity is a scalar, or False if it is an array-like object.

    Note

    This is subtly different from `numpy.isscalar` in that `numpy.isscalar` returns False for a zero-dimensional array (e.g. `np.array(1)`), while this is True for quantities, since quantities cannot represent true numpy scalars.

  si

    Returns a copy of the current `Quantity` instance with SI units. The value of the resulting object will be scaled.

  unit

    A `UnitBase` object representing the unit of this quantity.

  value

    The numerical value of this instance.

    See also

    `to_value`

      Get the numerical value in a given unit.

  Methods Documentation

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

    Returns True if all elements evaluate to True.

    Refer to `numpy.all` for full documentation.

    See also

    `numpy.all`

      equivalent function

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

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

    Refer to `numpy.any` for full documentation.

    See also

    `numpy.any`

      equivalent function

  argmax(axis=None, out=None, *, keepdims=False)

    Return indices of the maximum values along the given axis.

    Refer to `numpy.argmax` for full documentation.

    See also

    `numpy.argmax`

      equivalent function

  argmin(axis=None, out=None, *, keepdims=False)

    Return indices of the minimum values along the given axis.

    Refer to `numpy.argmin` for detailed documentation.

    See also

    `numpy.argmin`

      equivalent function

  argsort(axis=-1, kind=None, order=None, *, stable=None)

    Returns the indices that would sort this array.

    Refer to `numpy.argsort` for full documentation.

    See also

    `numpy.argsort`

      equivalent function

  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.

    See also

    `numpy.choose`

      equivalent function

  decompose(bases=())

    Generates a new `Quantity` with the units decomposed. Decomposed units have only irreducible units in them (see `astropy.units.UnitBase.decompose`).

    Parameters:
      bases python:sequence of `UnitBase`, optional

        The bases to decompose into. When not provided, decomposes down to any irreducible units. When provided, the decomposed result will only contain the given units. This will raises a `UnitsError` if it’s not possible to do so.

    Returns:
      newq `Quantity`

        A new object equal to this quantity with units decomposed.

  diff(n=1, axis=-1)
  dot(other, /, out=None)

    Refer to `numpy.dot()` for full documentation.

    See also

    `numpy.dot`

      equivalent function

  dump(file)

    Not implemented, use `.value.dump()` instead.

  dumps()

    Not implemented, use `.value.dumps()` instead.

  ediff1d(to_end=None, to_begin=None)
  fill(value)

    Fill the array with a scalar value.

    Parameters:
      value scalar

        All elements of `a` will be assigned this value.

    Examples

        >>> import numpy as np
        >>> a = np.array([1, 2])
        >>> a.fill(0)
        >>> a
        array([0, 0])
        >>> a = np.empty(2)
        >>> a.fill(1)
        >>> a
        array([1.,  1.])

    Fill expects a scalar value and always behaves the same as assigning to a single array element. The following is a rare example where this distinction is important:

        >>> a = np.array([None, None], dtype=object)
        >>> a[0] = np.array(3)
        >>> a
        array([array(3), None], dtype=object)
        >>> a.fill(np.array(3))
        >>> a
        array([array(3), array(3)], dtype=object)

    Where other forms of assignments will unpack the array being assigned:

        >>> a[...] = np.array(3)
        >>> a
        array([3, 3], dtype=object)

  insert(obj, values, axis=None)

    Insert values along the given axis before the given indices and return a new `Quantity` object.

    This is a thin wrapper around the `numpy.insert` function.

    Parameters:
      obj `python:int`, `slice` or python:sequence of `python:int`

        Object that defines the index or indices before which `values` is inserted.

      values numpy:array_like

        Values to insert. If the type of `values` is different from that of quantity, `values` is converted to the matching type. `values` should be shaped so that it can be broadcast appropriately The unit of `values` must be consistent with this quantity.

      axis `python:int`, optional

        Axis along which to insert `values`. If `axis` is None then the quantity array is flattened before insertion.

    Returns:
      out `Quantity`

        A copy of quantity with `values` inserted. Note that the insertion does not occur in-place: a new quantity array is returned.

    Examples

        >>> import astropy.units as u
        >>> q = [1, 2] * u.m
        >>> q.insert(0, 50 * u.cm)
        <Quantity [ 0.5,  1.,  2.] m>

        >>> q = [[1, 2], [3, 4]] * u.m
        >>> q.insert(1, [10, 20] * u.m, axis=0)
        <Quantity [[  1.,  2.],
                   [ 10., 20.],
                   [  3.,  4.]] m>

        >>> q.insert(1, 10 * u.m, axis=1)
        <Quantity [[  1., 10.,  2.],
                   [  3., 10.,  4.]] m>

  item(*args)

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

    Like `item()` except that it always returns a `Quantity`, not a Python scalar.

  mean(axis=None, dtype=None, out=None, *, keepdims=<no value>, where=<no value>)

    Returns the average of the array elements along given axis.

    Refer to `numpy.mean` for full documentation.

    See also

    `numpy.mean`

      equivalent function

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

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

    Refer to `numpy.put` for full documentation.

    See also

    `numpy.put`

      equivalent function

  round(decimals=0, out=None)

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

    Refer to `numpy.around` for full documentation.

    See also

    `numpy.around`

      equivalent function

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

    See also

    `numpy.searchsorted`

      equivalent function

  std(axis=None, dtype=None, out=None, ddof=0, *, keepdims=<no value>, where=<no value>, mean=<no value>)

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

    Refer to `numpy.std` for full documentation.

    See also

    `numpy.std`

      equivalent function

  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.

    See also

    `numpy.take`

      equivalent function

  to(unit, equivalencies=[], copy=True)

    Return a new `Quantity` object with the specified unit.

    Parameters:
      unit astropy:unit-like

        An object that represents the unit to convert to. Must be an `UnitBase` object or a string parseable by the `units` package.

      equivalencies `python:list` of `python:tuple`

        A list of equivalence pairs to try if the units are not directly convertible. See Equivalencies. If not provided or `[]`, class default equivalencies will be used (none for `Quantity`, but may be set for subclasses) If `None`, no equivalencies will be applied at all, not even any set globally or within a context.

      copy bool, optional

        If `True` (default), then the value is copied. Otherwise, a copy will only be made if necessary.

    See also

    `to_value`

      get the numerical value in a given unit.

  to_string(unit=None, precision=None, format=None, subfmt=None, *, formatter=None)

    Generate a string representation of the quantity and its unit.

    The behavior of this function can be altered via the `numpy.set_printoptions` function and its various keywords. The exception to this is the `threshold` keyword, which is controlled via the `[units.quantity]` configuration item `latex_array_threshold`. This is treated separately because the numpy default of 1000 is too big for most browsers to handle.

    Parameters:
      unit astropy:unit-like, optional

        Specifies the unit. If not provided, the unit used to initialize the quantity will be used.

      precision number, optional

        The level of decimal precision. If `None`, or not provided, it will be determined from NumPy print options.

      format `python:str`, optional

        The format of the result. If not provided, an unadorned string is returned. Supported values are:

        - ‘latex’: Return a LaTeX-formatted string

        - ‘latex_inline’: Return a LaTeX-formatted string that uses negative exponents instead of fractions

      formatter `python:str`, `python:callable()`, `python:dict`, optional

        The formatter to use for the value. If a string, it should be a valid format specifier using Python’s mini-language. If a callable, it will be treated as the default formatter for all values and will overwrite default Latex formatting for exponential notation and complex numbers. If a dict, it should map a specific type to a callable to be directly passed into `numpy.array2string`. If not provided, the default formatter will be used.

      subfmt `python:str`, optional

        Subformat of the result. For the moment, only used for `format='latex'` and `format='latex_inline'`. Supported values are:

        - ‘inline’: Use `$ ... $` as delimiters.

        - ‘display’: Use `$\displaystyle ... $` as delimiters.

    Returns:
      `python:str`

        A string with the contents of this Quantity

  to_value(unit=None, equivalencies=[])

    The numerical value, possibly in a different unit.

    Parameters:
      unit astropy:unit-like, optional

        The unit in which the value should be given. If not given or `None`, use the current unit.

      equivalencies `python:list` of `python:tuple`, optional

        A list of equivalence pairs to try if the units are not directly convertible (see Equivalencies). If not provided or `[]`, class default equivalencies will be used (none for `Quantity`, but may be set for subclasses). If `None`, no equivalencies will be applied at all, not even any set globally or within a context.

    Returns:
      value `ndarray` or scalar

        The value in the units specified. For arrays, this will be a view of the data if no unit conversion was necessary.

    See also

    `to`

      Get a new instance in a different unit.

  tobytes(order='C')

    Not implemented, use `.value.tobytes()` instead.

  tofile(fid, sep='', format='%s')

    Not implemented, use `.value.tofile()` instead.

  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 `item` method.

    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:
      none
    Returns:
      y `object`, or `python:list` of `object`, or `python:list` of `python:list` of `object`, or …

        The possibly nested list of array elements.

    Notes

    The array may be recreated via `a = np.array(a.tolist())`, although this may sometimes lose precision.

    Examples

    For a 1D array, `a.tolist()` is almost the same as `list(a)`, except that `tolist` changes numpy scalars to Python scalars:

        >>> import numpy as np
        >>> a = np.uint32([1, 2])
        >>> a_list = list(a)
        >>> a_list
        [np.uint32(1), np.uint32(2)]
        >>> type(a_list[0])
        <class 'numpy.uint32'>
        >>> a_tolist = a.tolist()
        >>> a_tolist
        [1, 2]
        >>> type(a_tolist[0])
        <class 'int'>

    Additionally, for a 2D array, `tolist` applies recursively:

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

    The base case for this recursion is a 0D array:

        >>> a = np.array(1)
        >>> list(a)
        Traceback (most recent call last):
          ...
        TypeError: iteration over a 0-d array
        >>> a.tolist()
        1

  tostring(order='C')

    Not implemented, use `.value.tostring()` instead.

  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.

    See also

    `numpy.trace`

      equivalent function

  var(axis=None, dtype=None, out=None, ddof=0, *, keepdims=<no value>, where=<no value>, mean=<no value>)

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

    Refer to `numpy.var` for full documentation.

    See also

    `numpy.var`

      equivalent function