Quantity¶

class
astropy.units.
Quantity
[source] [edit on github]¶ Bases:
numpy.ndarray
A
Quantity
represents a number with some associated unit.Parameters: value : number,
ndarray
,Quantity
object, or sequence ofQuantity
objects.unit :
UnitBase
instance, strdtype : ~numpy.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 input that cannot represent float (integer and bool) is converted to float.
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 givendtype
. (TheFalse
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
subok : bool, optional
ndmin : 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
andcopy=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.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 1D 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 arraylike 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 quantity. Methods Summary
all
([axis, out, keepdims])Returns True if all elements evaluate to True. any
([axis, out, keepdims])Returns True if any of the elements of a
evaluate to True.argmax
([axis, out])Return indices of the maximum values along the given axis. argmin
([axis, out])Return indices of the minimum values along the given axis of a
.argsort
([axis, kind, order])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. clip
([min, max, out])Return an array whose values are limited to [min, max]
.cumprod
([axis, dtype, out])Return the cumulative product of the elements along the given axis. cumsum
([axis, dtype, out])Return the cumulative sum of the elements along the given axis. decompose
([bases])Generates a new Quantity
with the units decomposed.diff
([n, axis])dot
(b[, out])Dot product of two arrays. dump
(file)Dump a pickle of the array to the specified file. dumps
()Returns the pickle of the array as a string. 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 standard Python scalar and return it. itemset
(*args)Insert scalar into an array (scalar is cast to array’s dtype, if possible) max
([axis, out])Return the maximum along a given axis. mean
([axis, dtype, out, keepdims])Returns the average of the array elements along given axis. min
([axis, out, keepdims])Return the minimum along a given axis. nansum
([axis, out, keepdims])prod
([axis, dtype, out, keepdims])Return the product of the array elements over the given axis ptp
([axis, out])Peak to peak (maximum  minimum) value along a given axis. put
(indices, values[, mode])Set a.flat[n] = values[n]
for alln
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. sum
([axis, dtype, out, keepdims])Return the sum of the array elements over the given axis. to
(unit[, equivalencies])Returns a new Quantity
object with the specified units.tofile
(fid[, sep, format])Write array to a file as text or binary (default). tolist
()Return the array as a (possibly nested) list. tostring
([order])Construct Python bytes containing the raw data bytes in the array. 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 1D iterator over the Quantity array.
This returns a
QuantityIterator
instance, which behaves the same as theflatiter
instance returned byflat
, and is similar to, but not a subclass of, Python’s builtin 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 arraylike object.Note
This is subtly different from
numpy.isscalar
in thatnumpy.isscalar
returns False for a zerodimensional 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.

value
¶ The numerical value of this quantity.
Methods Documentation

all
(axis=None, out=None, keepdims=False)[source] [edit on github]¶ 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=False)[source] [edit on github]¶ 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)[source] [edit on github]¶ 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)[source] [edit on github]¶ Return indices of the minimum values along the given axis of
a
.Refer to
numpy.argmin
for detailed documentation.See also
numpy.argmin
 equivalent function

argsort
(axis=1, kind='quicksort', order=None)[source] [edit on github]¶ 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')[source] [edit on github]¶ 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

clip
(min=None, max=None, out=None)[source] [edit on github]¶ 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.See also
numpy.clip
 equivalent function

cumprod
(axis=None, dtype=None, out=None)[source] [edit on github]¶ Return the cumulative product of the elements along the given axis.
Refer to
numpy.cumprod
for full documentation.See also
numpy.cumprod
 equivalent function

cumsum
(axis=None, dtype=None, out=None)[source] [edit on github]¶ Return the cumulative sum of the elements along the given axis.
Refer to
numpy.cumsum
for full documentation.See also
numpy.cumsum
 equivalent function

decompose
(bases=[])[source] [edit on github]¶ Generates a new
Quantity
with the units decomposed. Decomposed units have only irreducible units in them (seeastropy.units.UnitBase.decompose
).Parameters: bases : 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)[source] [edit on github]¶

dot
(b, out=None)[source] [edit on github]¶ Dot product of two arrays.
Refer to
numpy.dot
for full documentation.See also
numpy.dot
 equivalent function
Examples
>>> a = np.eye(2) >>> b = np.ones((2, 2)) * 2 >>> a.dot(b) array([[ 2., 2.], [ 2., 2.]])
This array method can be conveniently chained:
>>> a.dot(b).dot(b) array([[ 8., 8.], [ 8., 8.]])

dump
(file)[source] [edit on github]¶ Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
Parameters: file : str
A string naming the dump file.

dumps
()[source] [edit on github]¶ Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an array.
Parameters: None

ediff1d
(to_end=None, to_begin=None)[source] [edit on github]¶

fill
(value)[source] [edit on github]¶ Fill the array with a scalar value.
Parameters: value : scalar
All elements of
a
will be assigned this value.Examples
>>> a = np.array([1, 2]) >>> a.fill(0) >>> a array([0, 0]) >>> a = np.empty(2) >>> a.fill(1) >>> a array([ 1., 1.])

insert
(obj, values, axis=None)[source] [edit on github]¶ 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 : int, slice or sequence of ints
Object that defines the index or indices before which
values
is inserted.values : arraylike
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 ofvalues
must be consistent with this quantity.axis : int, optional
Axis along which to insert
values
. Ifaxis
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 inplace: 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)[source] [edit on github]¶ Copy an element of an array to a standard Python scalar and return it.
Parameters: *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 ndindex into the array.
Returns: z : Standard Python scalar object
A copy of the specified element of the array as a suitable Python scalar
Notes
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.Examples
>>> x = np.random.randint(9, size=(3, 3)) >>> x array([[3, 1, 7], [2, 8, 3], [8, 5, 3]]) >>> x.item(3) 2 >>> x.item(7) 5 >>> x.item((0, 1)) 1 >>> x.item((2, 2)) 3
 none: in this case, the method only works for arrays
with one element (

itemset
(*args)[source] [edit on github]¶ 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 thana[args] = item
. The item should be a scalar value andargs
must select a single item in the arraya
.Parameters: *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.Notes
Compared to indexing syntax,
itemset
provides some speed increase for placing a scalar into a particular location in anndarray
, if you must do this. However, generally this is discouraged: among other problems, it complicates the appearance of the code. Also, when usingitemset
(anditem
) inside a loop, be sure to assign the methods to a local variable to avoid the attribute lookup at each loop iteration.Examples
>>> x = np.random.randint(9, size=(3, 3)) >>> x array([[3, 1, 7], [2, 8, 3], [8, 5, 3]]) >>> x.itemset(4, 0) >>> x.itemset((2, 2), 9) >>> x array([[3, 1, 7], [2, 0, 3], [8, 5, 9]])

max
(axis=None, out=None)[source] [edit on github]¶ Return the maximum along a given axis.
Refer to
numpy.amax
for full documentation.See also
numpy.amax
 equivalent function

mean
(axis=None, dtype=None, out=None, keepdims=False)[source] [edit on github]¶ Returns the average of the array elements along given axis.
Refer to
numpy.mean
for full documentation.See also
numpy.mean
 equivalent function

min
(axis=None, out=None, keepdims=False)[source] [edit on github]¶ Return the minimum along a given axis.
Refer to
numpy.amin
for full documentation.See also
numpy.amin
 equivalent function

nansum
(axis=None, out=None, keepdims=False)[source] [edit on github]¶

prod
(axis=None, dtype=None, out=None, keepdims=False)[source] [edit on github]¶ Return the product of the array elements over the given axis
Refer to
numpy.prod
for full documentation.See also
numpy.prod
 equivalent function

ptp
(axis=None, out=None)[source] [edit on github]¶ Peak to peak (maximum  minimum) value along a given axis.
Refer to
numpy.ptp
for full documentation.See also
numpy.ptp
 equivalent function

put
(indices, values, mode='raise')[source] [edit on github]¶ Set
a.flat[n] = values[n]
for alln
in indices.Refer to
numpy.put
for full documentation.See also
numpy.put
 equivalent function

round
(decimals=0, out=None)[source] [edit on github]¶ 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)[source] [edit on github]¶ 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=False)[source] [edit on github]¶ Returns the standard deviation of the array elements along given axis.
Refer to
numpy.std
for full documentation.See also
numpy.std
 equivalent function

sum
(axis=None, dtype=None, out=None, keepdims=False)[source] [edit on github]¶ Return the sum of the array elements over the given axis.
Refer to
numpy.sum
for full documentation.See also
numpy.sum
 equivalent function

to
(unit, equivalencies=[])[source] [edit on github]¶ Returns a new
Quantity
object with the specified units.Parameters: unit :
UnitBase
instance, strequivalencies : list of equivalence pairs, 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 forQuantity
, but may be set for subclasses) IfNone
, no equivalencies will be applied at all, not even any set globally or within a context.

tofile
(fid, sep="", format="%s")[source] [edit on github]¶ 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: fid : file or str
An open file object, or a string containing a filename.
sep : str
Separator between array items for text output. If “” (empty), a binary file is written, equivalent to
file.write(a.tobytes())
.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.
Notes
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.

tolist
()[source] [edit on github]¶ Return the array as a (possibly nested) list.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible Python type.
Parameters: none
Returns: y : list
The possibly nested list of array elements.
Notes
The array may be recreated,
a = np.array(a.tolist())
.Examples
>>> a = np.array([1, 2]) >>> a.tolist() [1, 2] >>> a = np.array([[1, 2], [3, 4]]) >>> list(a) [array([1, 2]), array([3, 4])] >>> a.tolist() [[1, 2], [3, 4]]

tostring
(order='C')[source] [edit on github]¶ 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 can be produced in either ‘C’ or ‘Fortran’, or ‘Any’ order (the default is ‘C’order). ‘Any’ order means Corder unless the F_CONTIGUOUS flag in the array is set, in which case it means ‘Fortran’ order.
This function is a compatibility alias for tobytes. Despite its name it returns bytes not strings.
Parameters: order : {‘C’, ‘F’, None}, optional
Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array.
Returns: s : bytes
Python bytes exhibiting a copy of
a
‘s raw data.Examples
>>> x = np.array([[0, 1], [2, 3]]) >>> x.tobytes() b'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00' >>> x.tobytes('C') == x.tobytes() True >>> x.tobytes('F') b'\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00'

trace
(offset=0, axis1=0, axis2=1, dtype=None, out=None)[source] [edit on github]¶ 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=False)[source] [edit on github]¶ Returns the variance of the array elements, along given axis.
Refer to
numpy.var
for full documentation.See also
numpy.var
 equivalent function
