Quantity#
- class astropy.units.Quantity(value, unit=None, dtype=<class 'numpy.inexact'>, copy=True, order=None, subok=False, ndmin=0)[source]#
Bases:
ndarrayA
Quantityrepresents a number with some associated unit.See also: https://docs.astropy.org/en/stable/units/quantity.html
- Parameters:
- valuenumber,
ndarray,Quantity(sequence), orstr The numerical value of this quantity in the units given by unit. If a
Quantityor sequence of them (or any other valid object with aunitattribute), creates a newQuantityobject, converting tounitunits as needed. If a string, it is converted to a number orQuantity, depending on whether a unit is present.- unitastropy:unit-like
An object that represents the unit associated with the input value. Must be an
UnitBaseobject or a string parseable by theunitspackage.- 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 normalnumpy.dtypeintrospection is used, e.g. preventing upcasting of integers.- copybool, 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. (TheFalseoption 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 aQuantityandcopy=False.- subokbool, optional
If
False(default), the returned array will be forced to be aQuantity. Otherwise,Quantitysubclasses will be passed through, or a subclass appropriate for the unit will be used (such asDexforu.dex(u.AA)).- 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
Quantityandcopy=False.
- valuenumber,
- Raises:
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
dtypeargument is explicitly specified, integer or (non-Quantity) object inputs are converted tofloatby default.Attributes Summary
Returns a copy of the current
Quantityinstance with CGS units.A list of equivalencies that will be applied by default during unit conversions.
A 1-D iterator over the Quantity array.
Container for meta information like name, description, format.
True if the
valueof this quantity is a scalar, or False if it is an array-like object.Returns a copy of the current
Quantityinstance with SI units.A
UnitBaseobject representing the unit of this quantity.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
aevaluate 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])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
Quantitywith the units decomposed.diff([n, axis])dot(b[, out])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
Quantityobject.item(*args)Copy an element of an array to a scalar Quantity and return it.
itemset(*args)Insert scalar into an array (scalar is cast to array's dtype, if possible)
mean([axis, dtype, out, keepdims, where])Returns the average of the array elements along given axis.
nansum([axis, out, keepdims, initial, where])Deprecated since version 5.3.
put(indices, values[, mode])Set
a.flat[n] = values[n]for allnin indices.round([decimals, out])Return
awith 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, where])Returns the standard deviation of the array elements along given axis.
take(indices[, axis, out, mode])Return an array formed from the elements of
aat the given indices.to(unit[, equivalencies, copy])Return a new
Quantityobject 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, where])Returns the variance of the array elements, along given axis.
Attributes Documentation
- cgs#
Returns a copy of the current
Quantityinstance 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
QuantityIteratorinstance, which behaves the same as theflatiterinstance returned byflat, 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
valueof this quantity is a scalar, or False if it is an array-like object.Note
This is subtly different from
numpy.isscalarin thatnumpy.isscalarreturns 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
Quantityinstance with SI units. The value of the resulting object will be scaled.
- value#
The numerical value of this instance.
See also
to_valueGet the numerical value in a given unit.
Methods Documentation
- all(axis=None, out=None, keepdims=False, *, where=True)[source]#
Returns True if all elements evaluate to True.
Refer to
numpy.allfor full documentation.See also
numpy.allequivalent function
- any(axis=None, out=None, keepdims=False, *, where=True)[source]#
Returns True if any of the elements of
aevaluate to True.Refer to
numpy.anyfor full documentation.See also
numpy.anyequivalent function
- argmax(axis=None, out=None, *, keepdims=False)[source]#
Return indices of the maximum values along the given axis.
Refer to
numpy.argmaxfor full documentation.See also
numpy.argmaxequivalent function
- argmin(axis=None, out=None, *, keepdims=False)[source]#
Return indices of the minimum values along the given axis.
Refer to
numpy.argminfor detailed documentation.See also
numpy.argminequivalent function
- argsort(axis=-1, kind=None, order=None)[source]#
Returns the indices that would sort this array.
Refer to
numpy.argsortfor full documentation.See also
numpy.argsortequivalent function
- choose(choices, out=None, mode='raise')[source]#
Use an index array to construct a new array from a set of choices.
Refer to
numpy.choosefor full documentation.See also
numpy.chooseequivalent function
- decompose(bases=[])[source]#
Generates a new
Quantitywith the units decomposed. Decomposed units have only irreducible units in them (seeastropy.units.UnitBase.decompose).- Parameters:
- basessequence 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
UnitsErrorif it’s not possible to do so.
- basessequence of
- Returns:
- newq
Quantity A new object equal to this quantity with units decomposed.
- newq
- fill(value)[source]#
Fill the array with a scalar value.
- Parameters:
- valuescalar
All elements of
awill 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.])
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)[source]#
Insert values along the given axis before the given indices and return a new
Quantityobject.This is a thin wrapper around the
numpy.insertfunction.- Parameters:
- obj
int,sliceor sequence ofint Object that defines the index or indices before which
valuesis inserted.- valuesarray_like
Values to insert. If the type of
valuesis different from that of quantity,valuesis converted to the matching type.valuesshould be shaped so that it can be broadcast appropriately The unit ofvaluesmust be consistent with this quantity.- axis
int, optional Axis along which to insert
values. Ifaxisis None then the quantity array is flattened before insertion.
- obj
- Returns:
- out
Quantity A copy of quantity with
valuesinserted. Note that the insertion does not occur in-place: a new quantity array is returned.
- out
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]#
Copy an element of an array to a scalar Quantity and return it.
Like
item()except that it always returns aQuantity, not a Python scalar.
- itemset(*args)[source]#
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 andargsmust select a single item in the arraya.- Parameters:
- *argsArguments
If one argument: a scalar, only used in case
ais 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,
itemsetprovides 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 look-up at each loop iteration.Examples
>>> np.random.seed(123) >>> x = np.random.randint(9, size=(3, 3)) >>> x array([[2, 2, 6], [1, 3, 6], [1, 0, 1]]) >>> x.itemset(4, 0) >>> x.itemset((2, 2), 9) >>> x array([[2, 2, 6], [1, 0, 6], [1, 0, 9]])
- mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)[source]#
Returns the average of the array elements along given axis.
Refer to
numpy.meanfor full documentation.See also
numpy.meanequivalent function
- nansum(axis=None, out=None, keepdims=False, *, initial=None, where=True)[source]#
Deprecated since version 5.3: The nansum method is deprecated and may be removed in a future version. Use np.nansum instead.
- put(indices, values, mode='raise')[source]#
Set
a.flat[n] = values[n]for allnin indices.Refer to
numpy.putfor full documentation.See also
numpy.putequivalent function
- round(decimals=0, out=None)[source]#
Return
awith each element rounded to the given number of decimals.Refer to
numpy.aroundfor full documentation.See also
numpy.aroundequivalent function
- searchsorted(v, side='left', sorter=None)[source]#
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see
numpy.searchsortedSee also
numpy.searchsortedequivalent function
- std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)[source]#
Returns the standard deviation of the array elements along given axis.
Refer to
numpy.stdfor full documentation.See also
numpy.stdequivalent function
- take(indices, axis=None, out=None, mode='raise')[source]#
Return an array formed from the elements of
aat the given indices.Refer to
numpy.takefor full documentation.See also
numpy.takeequivalent function
- to(unit, equivalencies=[], copy=True)[source]#
Return a new
Quantityobject with the specified unit.- Parameters:
- unitastropy:unit-like
An object that represents the unit to convert to. Must be an
UnitBaseobject or a string parseable by theunitspackage.- equivalencies
listoftuple 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.- copybool, optional
If
True(default), then the value is copied. Otherwise, a copy will only be made if necessary.
See also
to_valueget the numerical value in a given unit.
- to_string(unit=None, precision=None, format=None, subfmt=None)[source]#
Generate a string representation of the quantity and its unit.
The behavior of this function can be altered via the
numpy.set_printoptionsfunction and its various keywords. The exception to this is thethresholdkeyword, which is controlled via the[units.quantity]configuration itemlatex_array_threshold. This is treated separately because the numpy default of 1000 is too big for most browsers to handle.- Parameters:
- unitastropy:unit-like, optional
Specifies the unit. If not provided, the unit used to initialize the quantity will be used.
- precisionnumber, optional
The level of decimal precision. If
None, or not provided, it will be determined from NumPy print options.- format
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
- subfmt
str, optional Subformat of the result. For the moment, only used for
format='latex'andformat='latex_inline'. Supported values are:‘inline’: Use
$ ... $as delimiters.‘display’: Use
$\displaystyle ... $as delimiters.
- Returns:
strA string with the contents of this Quantity
- to_value(unit=None, equivalencies=[])[source]#
The numerical value, possibly in a different unit.
- Parameters:
- unitastropy:unit-like, optional
The unit in which the value should be given. If not given or
None, use the current unit.- equivalencies
listoftuple, 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.
- Returns:
See also
toGet a new instance in a different unit.
- tolist()[source]#
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
itemfunction.If
a.ndimis 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:
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 aslist(a), except thattolistchanges numpy scalars to Python scalars:>>> a = np.uint32([1, 2]) >>> a_list = list(a) >>> a_list [1, 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,
tolistapplies 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
- trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)[source]#
Return the sum along diagonals of the array.
Refer to
numpy.tracefor full documentation.See also
numpy.traceequivalent function