InitialCMCTable
- class cosmic.sample.initialcmctable.InitialCMCTable(data=None, index: Axes | None = None, columns: Axes | None = None, dtype: Dtype | None = None, copy: bool | None = None)
Bases:
DataFrame
- classmethod InitialCMCBinaries(index, id1, k1, m1, Reff1, id2, k2, m2, Reff2, a, e)
Create A Table of CMC Binaries
- Parameters:
- m1float
Primary mass [Msun]
- m2float
Secondary mass [Msun]
- porbfloat
Orbital period [days]
- eccfloat
Eccentricity
- kstar1array
0-14 Initial stellar type of the larger object; main sequence stars are 0 if m < 0.7 Msun and 1 otherwise
- kstar2array
0-14 Initial stellar type of the smaller object; main sequence stars are 0 if m < 0.7 Msun and 1 otherwise
- metallicityfloat
Metallicity of the binaries; Z_sun = 0.02
- **kwargs
- binfracfloat
System-specific probability of the primary star being in a binary
- Returns:
- InitialBinariesDataFrame
Single binary initial conditions
- classmethod InitialCMCSingles(id_idx, k, m, Reff, r, vr, vt, binind)
Create A Table of CMC Singles
- Parameters:
- m1float
Primary mass [Msun]
- m2float
Secondary mass [Msun]
- porbfloat
Orbital period [days]
- eccfloat
Eccentricity
- kstar1array
0-14 Initial stellar type of the larger object; main sequence stars are 0 if m < 0.7 Msun and 1 otherwise
- kstar2array
0-14 Initial stellar type of the smaller object; main sequence stars are 0 if m < 0.7 Msun and 1 otherwise
- metallicityfloat
Metallicity of the binaries; Z_sun = 0.02
- **kwargs
- binfracfloat
System-specific probability of the primary star being in a binary
- Returns:
- InitialBinariesDataFrame
Single binary initial conditions
- ScaleCentralBHMass(Mtotal)
Rescale the central BH mass; needed since this is a class attribute Parameters ———-
- Mtotalfloat
total mass of the cluster
- classmethod ScaleToNBodyUnits(Singles, Binaries, virial_radius=1, central_bh=0, scale_with_central_bh=False)
- Rescale the single masses, radii, and velocities into N-body units
- i.e. sum m = M = 1
Kinetic Energy = 0.25 Potential Energy = -0.5
Note that this is already done for r, vr, and vt from the profile generators. However, after the stellar masses are assigned we need to redo it, and the stellar radii and seperations need to be converted from RSUN to code units
- Parameters:
- SinglesDataFrame
Pandas DataFrame from the InitialCMCSingles function
- BinariesDataFrame
Pandas DataFrame from the InitialCMCSingles function
- virial_radiusfloat
Virial radius of the cluster in parsec (default 1pc)
- Returns:
- None: Pandas dataframes are modified in place
- __annotations__ = {}
- __doc__ = None
- __module__ = 'cosmic.sample.initialcmctable'
- central_bh = 0.0
- mass_of_cluster = None
- metallicity = None
- classmethod read(filename)
Read Singles and Binaries to HDF5 or FITS file
- Parameters:
- filename(str)
Must end in “.fits” or “.hdf5/h5”
- Returns:
- SinglesDataFrame
Pandas DataFrame from the InitialCMCSingles function
- BinariesDataFrame
Pandas DataFrame from the InitialCMCBinaries function
- classmethod sampler(format_, *args, **kwargs)
Fetch a method to generate an initial binary sample
- Parameters:
- formatstr
the method name; Choose from ‘independent’ or ‘multidim’
- *args
the arguments necessary for the registered sample method; see help(InitialCMCTable.sampler(‘independent’) to see the arguments necessary for the independent sample
- The available named formats are:
- ============== …
Format …
- ============== …
cmc …
- cmc_point_mass …
- ============== …
- scale_with_central_bh = False
- scaled_to_nbody_units = False
- tidal_radius = None
- virial_radius = None
- classmethod write(Singles, Binaries, filename='input.hdf5', **kwargs)
Save Singles and Binaries to HDF5 or FITS file
- Parameters:
- SinglesDataFrame
Pandas DataFrame from the InitialCMCSingles function
- BinariesDataFrame
Pandas DataFrame from the InitialCMCBinaries function
- filename(str)
Must end in “.fits” or “.hdf5/h5”
- Returns:
- None:
- class cosmic.sample.initialcmctable.Table(data=None, masked=False, names=None, dtype=None, meta=None, copy=True, rows=None, copy_indices=True, units=None, descriptions=None, **kwargs)
Bases:
object
A class to represent tables of heterogeneous data.
~astropy.table.Table provides a class for heterogeneous tabular data. A key enhancement provided by the ~astropy.table.Table class over e.g. a numpy structured array is the ability to easily modify the structure of the table by adding or removing columns, or adding new rows of data. In addition table and column metadata are fully supported.
~astropy.table.Table differs from ~astropy.nddata.NDData by the assumption that the input data consists of columns of homogeneous data, where each column has a unique identifier and may contain additional metadata such as the data unit, format, and description.
See also: https://docs.astropy.org/en/stable/table/
- Parameters:
- datanumpy ndarray, dict, list, table-like object, optional
Data to initialize table.
- maskedbool, optional
Specify whether the table is masked.
- nameslist, optional
Specify column names.
- dtypelist, optional
Specify column data types.
- metadict, optional
Metadata associated with the table.
- copybool, optional
Copy the input column data and make a deep copy of the input meta. Default is True.
- rowsnumpy ndarray, list of list, optional
Row-oriented data for table instead of
data
argument.- copy_indicesbool, optional
Copy any indices in the input data. Default is True.
- unitslist, dict, optional
List or dict of units to apply to columns.
- descriptionslist, dict, optional
List or dict of descriptions to apply to columns.
- **kwargsdict, optional
Additional keyword args when converting table-like object.
- class Column(data=None, name=None, dtype=None, shape=(), length=0, description=None, unit=None, format=None, meta=None, copy=None, copy_indices=True)
Bases:
BaseColumn
Define a data column for use in a Table object.
- Parameters:
- datalist, ndarray, or None
Column data values
- namestr
Column name and key for reference within Table
- dtype~numpy.dtype-like
Data type for column
- shapetuple or ()
Dimensions of a single row element in the column data
- lengthint or 0
Number of row elements in column data
- descriptionstr or None
Full description of column
- unitstr or None
Physical unit
- formatstr, None, or callable
Format string for outputting column values. This can be an “old-style” (
format % value
) or “new-style” (str.format) format specification string or a function or any callable object that accepts a single value and returns a string.- metadict-like or None
Meta-data associated with the column
Examples
A Column can be created in two different ways:
Provide a
data
value but notshape
orlength
(which are inferred from the data).Examples:
col = Column(data=[1, 2], name='name') # shape=(2,) col = Column(data=[[1, 2], [3, 4]], name='name') # shape=(2, 2) col = Column(data=[1, 2], name='name', dtype=float) col = Column(data=np.array([1, 2]), name='name') col = Column(data=['hello', 'world'], name='name')
The
dtype
argument can be any value which is an acceptable fixed-size data-type initializer for the numpy.dtype() method. See https://numpy.org/doc/stable/reference/arrays.dtypes.html. Examples include:Python non-string type (float, int, bool)
Numpy non-string type (e.g. np.float32, np.int64, np.bool_)
Numpy.dtype array-protocol type strings (e.g. ‘i4’, ‘f8’, ‘S15’)
If no
dtype
value is provide then the type is inferred usingnp.array(data)
.Provide
length
and optionallyshape
, but notdata
Examples:
col = Column(name='name', length=5) col = Column(name='name', dtype=int, length=10, shape=(3,4))
The default
dtype
isnp.float64
. Theshape
argument is the array shape of a single cell in the column.
To access the
Column
data as a raw numpy.ndarray object, you can use one of thedata
orvalue
attributes (which are equivalent):col.data col.value
- __bytes__()
- __doc__ = 'Define a data column for use in a Table object.\n\n Parameters\n ----------\n data : list, ndarray, or None\n Column data values\n name : str\n Column name and key for reference within Table\n dtype : `~numpy.dtype`-like\n Data type for column\n shape : tuple or ()\n Dimensions of a single row element in the column data\n length : int or 0\n Number of row elements in column data\n description : str or None\n Full description of column\n unit : str or None\n Physical unit\n format : str, None, or callable\n Format string for outputting column values. This can be an\n "old-style" (``format % value``) or "new-style" (`str.format`)\n format specification string or a function or any callable object that\n accepts a single value and returns a string.\n meta : dict-like or None\n Meta-data associated with the column\n\n Examples\n --------\n A Column can be created in two different ways:\n\n - Provide a ``data`` value but not ``shape`` or ``length`` (which are\n inferred from the data).\n\n Examples::\n\n col = Column(data=[1, 2], name=\'name\') # shape=(2,)\n col = Column(data=[[1, 2], [3, 4]], name=\'name\') # shape=(2, 2)\n col = Column(data=[1, 2], name=\'name\', dtype=float)\n col = Column(data=np.array([1, 2]), name=\'name\')\n col = Column(data=[\'hello\', \'world\'], name=\'name\')\n\n The ``dtype`` argument can be any value which is an acceptable\n fixed-size data-type initializer for the numpy.dtype() method. See\n `<https://numpy.org/doc/stable/reference/arrays.dtypes.html>`_.\n Examples include:\n\n - Python non-string type (float, int, bool)\n - Numpy non-string type (e.g. np.float32, np.int64, np.bool\\_)\n - Numpy.dtype array-protocol type strings (e.g. \'i4\', \'f8\', \'S15\')\n\n If no ``dtype`` value is provide then the type is inferred using\n ``np.array(data)``.\n\n - Provide ``length`` and optionally ``shape``, but not ``data``\n\n Examples::\n\n col = Column(name=\'name\', length=5)\n col = Column(name=\'name\', dtype=int, length=10, shape=(3,4))\n\n The default ``dtype`` is ``np.float64``. The ``shape`` argument is the\n array shape of a single cell in the column.\n\n To access the ``Column`` data as a raw `numpy.ndarray` object, you can use\n one of the ``data`` or ``value`` attributes (which are equivalent)::\n\n col.data\n col.value\n '
- __eq__(other)
Return self==value.
- __ge__(other)
Return self>=value.
- __gt__(other)
Return self>value.
- __hash__ = None
- __le__(other)
Return self<=value.
- __lt__(other)
Return self<value.
- __module__ = 'astropy.table.column'
- __ne__(other)
Return self!=value.
- static __new__(cls, data=None, name=None, dtype=None, shape=(), length=0, description=None, unit=None, format=None, meta=None, copy=None, copy_indices=True)
- __repr__()
Return repr(self).
- __setattr__(item, value)
Implement setattr(self, name, value).
- __setitem__(index, value)
Set self[key] to value.
- __str__()
Return str(self).
- _base_repr_(html=False)
- _check_string_truncate(value)
Emit a warning if any elements of
value
will be truncated whenvalue
is assigned to self.
- _repr_html_()
- convert_unit_to(new_unit, equivalencies=[])
Converts the values of the column in-place from the current unit to the given unit.
To change the unit associated with this column without actually changing the data values, simply set the
unit
property.- Parameters:
- new_unitstr or astropy.units.UnitBase instance
The unit to convert to.
- equivalencieslist of tuple
A list of equivalence pairs to try if the unit are not directly convertible. See Equivalencies.
- Raises:
- astropy.units.UnitsError
If units are inconsistent
- copy(order='C', data=None, copy_data=True)
Return a copy of the current instance.
If
data
is supplied then a view (reference) ofdata
is used, andcopy_data
is ignored.- Parameters:
- order{‘C’, ‘F’, ‘A’, ‘K’}, optional
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 ofa
as closely as possible. (Note that this function and :func:numpy.copy are very similar, but have different default values for their order= arguments.) Default is ‘C’.- dataarray, optional
If supplied then use a view of
data
instead of the instance data. This allows copying the instance attributes and meta.- copy_databool, optional
Make a copy of the internal numpy array instead of using a reference. Default is True.
- Returns:
- colColumn or MaskedColumn
Copy of the current column (same type as original)
- insert(obj, values, axis=0)
Insert values before the given indices in the column and return a new ~astropy.table.Column object.
- Parameters:
- objint, slice or sequence of int
Object that defines the index or indices before which
values
is inserted.- valuesarray-like
Value(s) to insert. If the type of
values
is different from that of the column,values
is converted to the matching type.values
should be shaped so that it can be broadcast appropriately.- axisint, optional
Axis along which to insert
values
. Ifaxis
is None then the column array is flattened before insertion. Default is 0, which will insert a row.
- Returns:
- out~astropy.table.Column
A copy of column with
values
andmask
inserted. Note that the insertion does not occur in-place: a new column is returned.
- more(max_lines=None, show_name=True, show_unit=False)
Interactively browse column with a paging interface.
Supported keys:
f, <space> : forward one page b : back one page r : refresh same page n : next row p : previous row < : go to beginning > : go to end q : quit browsing h : print this help
- Parameters:
- max_linesint
Maximum number of lines in table output.
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is False.
- property name
The name of this column.
- pformat(max_lines=None, show_name=True, show_unit=False, show_dtype=False, html=False)
Return a list of formatted string representation of column values.
If no value of
max_lines
is supplied then the height of the screen terminal is used to setmax_lines
. If the terminal height cannot be determined then the default will be determined using theastropy.conf.max_lines
configuration item. If a negative value ofmax_lines
is supplied then there is no line limit applied.- Parameters:
- max_linesint
Maximum lines of output (header + data rows)
- show_namebool
Include column name. Default is True.
- show_unitbool
Include a header row for unit. Default is False.
- show_dtypebool
Include column dtype. Default is False.
- htmlbool
Format the output as an HTML table. Default is False.
- Returns:
- lineslist
List of lines with header and formatted column values
- pprint(max_lines=None, show_name=True, show_unit=False, show_dtype=False)
Print a formatted string representation of column values.
If no value of
max_lines
is supplied then the height of the screen terminal is used to setmax_lines
. If the terminal height cannot be determined then the default will be determined using theastropy.conf.max_lines
configuration item. If a negative value ofmax_lines
is supplied then there is no line limit applied.- Parameters:
- max_linesint
Maximum number of values in output
- show_namebool
Include column name. Default is True.
- show_unitbool
Include a header row for unit. Default is False.
- show_dtypebool
Include column dtype. Default is True.
- property quantity
A view of this table column as a ~astropy.units.Quantity object with units given by the Column’s unit parameter.
- to(unit, equivalencies=[], **kwargs)
Converts this table column to a ~astropy.units.Quantity object with the requested units.
- Parameters:
- unitunit-like
The unit to convert to (i.e., a valid argument to the
astropy.units.Quantity.to()
method).- equivalencieslist of tuple
Equivalencies to use for this conversion. See
astropy.units.Quantity.to()
for more details.
- Returns:
- quantity~astropy.units.Quantity
A quantity object with the contents of this column in the units
unit
.
- property unit
The unit associated with this column. May be a string or a astropy.units.UnitBase instance.
Setting the
unit
property does not change the values of the data. To perform a unit conversion, useconvert_unit_to
.
- property ColumnClass
- class MaskedColumn(data=None, name=None, mask=None, fill_value=None, dtype=None, shape=(), length=0, description=None, unit=None, format=None, meta=None, copy=None, copy_indices=True)
Bases:
Column
,_MaskedColumnGetitemShim
,MaskedArray
Define a masked data column for use in a Table object.
- Parameters:
- datalist, ndarray, or None
Column data values
- namestr
Column name and key for reference within Table
- masklist, ndarray or None
Boolean mask for which True indicates missing or invalid data
- fill_valuefloat, int, str, or None
Value used when filling masked column elements
- dtype~numpy.dtype-like
Data type for column
- shapetuple or ()
Dimensions of a single row element in the column data
- lengthint or 0
Number of row elements in column data
- descriptionstr or None
Full description of column
- unitstr or None
Physical unit
- formatstr, None, or callable
Format string for outputting column values. This can be an “old-style” (
format % value
) or “new-style” (str.format) format specification string or a function or any callable object that accepts a single value and returns a string.- metadict-like or None
Meta-data associated with the column
Examples
A MaskedColumn is similar to a Column except that it includes
mask
andfill_value
attributes. It can be created in two different ways:Provide a
data
value but notshape
orlength
(which are inferred from the data).Examples:
col = MaskedColumn(data=[1, 2], name='name') col = MaskedColumn(data=[1, 2], name='name', mask=[True, False]) col = MaskedColumn(data=[1, 2], name='name', dtype=float, fill_value=99)
The
mask
argument will be cast as a boolean array and specifies which elements are considered to be missing or invalid.The
dtype
argument can be any value which is an acceptable fixed-size data-type initializer for the numpy.dtype() method. See https://numpy.org/doc/stable/reference/arrays.dtypes.html. Examples include:Python non-string type (float, int, bool)
Numpy non-string type (e.g. np.float32, np.int64, np.bool_)
Numpy.dtype array-protocol type strings (e.g. ‘i4’, ‘f8’, ‘S15’)
If no
dtype
value is provide then the type is inferred usingnp.array(data)
. Whendata
is provided then theshape
andlength
arguments are ignored.Provide
length
and optionallyshape
, but notdata
Examples:
col = MaskedColumn(name='name', length=5) col = MaskedColumn(name='name', dtype=int, length=10, shape=(3,4))
The default
dtype
isnp.float64
. Theshape
argument is the array shape of a single cell in the column.
To access the
Column
data as a raw numpy.ma.MaskedArray object, you can use one of thedata
orvalue
attributes (which are equivalent):col.data col.value
- __annotations__ = {}
- __doc__ = 'Define a masked data column for use in a Table object.\n\n Parameters\n ----------\n data : list, ndarray, or None\n Column data values\n name : str\n Column name and key for reference within Table\n mask : list, ndarray or None\n Boolean mask for which True indicates missing or invalid data\n fill_value : float, int, str, or None\n Value used when filling masked column elements\n dtype : `~numpy.dtype`-like\n Data type for column\n shape : tuple or ()\n Dimensions of a single row element in the column data\n length : int or 0\n Number of row elements in column data\n description : str or None\n Full description of column\n unit : str or None\n Physical unit\n format : str, None, or callable\n Format string for outputting column values. This can be an\n "old-style" (``format % value``) or "new-style" (`str.format`)\n format specification string or a function or any callable object that\n accepts a single value and returns a string.\n meta : dict-like or None\n Meta-data associated with the column\n\n Examples\n --------\n A MaskedColumn is similar to a Column except that it includes ``mask`` and\n ``fill_value`` attributes. It can be created in two different ways:\n\n - Provide a ``data`` value but not ``shape`` or ``length`` (which are\n inferred from the data).\n\n Examples::\n\n col = MaskedColumn(data=[1, 2], name=\'name\')\n col = MaskedColumn(data=[1, 2], name=\'name\', mask=[True, False])\n col = MaskedColumn(data=[1, 2], name=\'name\', dtype=float, fill_value=99)\n\n The ``mask`` argument will be cast as a boolean array and specifies\n which elements are considered to be missing or invalid.\n\n The ``dtype`` argument can be any value which is an acceptable\n fixed-size data-type initializer for the numpy.dtype() method. See\n `<https://numpy.org/doc/stable/reference/arrays.dtypes.html>`_.\n Examples include:\n\n - Python non-string type (float, int, bool)\n - Numpy non-string type (e.g. np.float32, np.int64, np.bool\\_)\n - Numpy.dtype array-protocol type strings (e.g. \'i4\', \'f8\', \'S15\')\n\n If no ``dtype`` value is provide then the type is inferred using\n ``np.array(data)``. When ``data`` is provided then the ``shape``\n and ``length`` arguments are ignored.\n\n - Provide ``length`` and optionally ``shape``, but not ``data``\n\n Examples::\n\n col = MaskedColumn(name=\'name\', length=5)\n col = MaskedColumn(name=\'name\', dtype=int, length=10, shape=(3,4))\n\n The default ``dtype`` is ``np.float64``. The ``shape`` argument is the\n array shape of a single cell in the column.\n\n To access the ``Column`` data as a raw `numpy.ma.MaskedArray` object, you can\n use one of the ``data`` or ``value`` attributes (which are equivalent)::\n\n col.data\n col.value\n '
- __module__ = 'astropy.table.column'
- static __new__(cls, data=None, name=None, mask=None, fill_value=None, dtype=None, shape=(), length=0, description=None, unit=None, format=None, meta=None, copy=None, copy_indices=True)
- __setitem__(index, value)
Set self[key] to value.
- _copy_attrs_slice(out)
- convert_unit_to(new_unit, equivalencies=[])
Converts the values of the column in-place from the current unit to the given unit.
To change the unit associated with this column without actually changing the data values, simply set the
unit
property.- Parameters:
- new_unitstr or astropy.units.UnitBase instance
The unit to convert to.
- equivalencieslist of tuple
A list of equivalence pairs to try if the unit are not directly convertible. See Equivalencies.
- Raises:
- astropy.units.UnitsError
If units are inconsistent
- copy(order='C', data=None, copy_data=True)
Return a copy of the current instance.
If
data
is supplied then a view (reference) ofdata
is used, andcopy_data
is ignored.- Parameters:
- order{‘C’, ‘F’, ‘A’, ‘K’}, optional
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 ofa
as closely as possible. (Note that this function and :func:numpy.copy are very similar, but have different default values for their order= arguments.) Default is ‘C’.- dataarray, optional
If supplied then use a view of
data
instead of the instance data. This allows copying the instance attributes and meta.- copy_databool, optional
Make a copy of the internal numpy array instead of using a reference. Default is True.
- Returns:
- colColumn or MaskedColumn
Copy of the current column (same type as original)
- property data
The plain MaskedArray data held by this column.
- property fill_value
The filling value of the masked array is a scalar. When setting, None will set to a default based on the data type.
Examples
>>> for dt in [np.int32, np.int64, np.float64, np.complex128]: ... np.ma.array([0, 1], dtype=dt).get_fill_value() ... np.int64(999999) np.int64(999999) np.float64(1e+20) np.complex128(1e+20+0j)
>>> x = np.ma.array([0, 1.], fill_value=-np.inf) >>> x.fill_value np.float64(-inf) >>> x.fill_value = np.pi >>> x.fill_value np.float64(3.1415926535897931)
Reset to default:
>>> x.fill_value = None >>> x.fill_value np.float64(1e+20)
- filled(fill_value=None)
Return a copy of self, with masked values filled with a given value.
- Parameters:
- fill_valuescalar; optional
The value to use for invalid entries (None by default). If None, the
fill_value
attribute of the array is used instead.
- Returns:
- filled_columnColumn
A copy of
self
with masked entries replaced by fill_value (be it the function argument or the attribute ofself
).
- 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. In this case it just adds the
mask_val
attribute.
- insert(obj, values, mask=None, axis=0)
Insert values along the given axis before the given indices and return a new ~astropy.table.MaskedColumn object.
- Parameters:
- objint, slice or sequence of int
Object that defines the index or indices before which
values
is inserted.- valuesarray-like
Value(s) to insert. If the type of
values
is different from that of the column,values
is converted to the matching type.values
should be shaped so that it can be broadcast appropriately.- maskbool or array-like
Mask value(s) to insert. If not supplied, and values does not have a mask either, then False is used.
- axisint, optional
Axis along which to insert
values
. Ifaxis
is None then the column array is flattened before insertion. Default is 0, which will insert a row.
- Returns:
- out~astropy.table.MaskedColumn
A copy of column with
values
andmask
inserted. Note that the insertion does not occur in-place: a new masked column is returned.
- more(max_lines=None, show_name=True, show_unit=False)
Interactively browse column with a paging interface.
Supported keys:
f, <space> : forward one page b : back one page r : refresh same page n : next row p : previous row < : go to beginning > : go to end q : quit browsing h : print this help
- Parameters:
- max_linesint
Maximum number of lines in table output.
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is False.
- property name
The name of this column.
- pformat(max_lines=None, show_name=True, show_unit=False, show_dtype=False, html=False)
Return a list of formatted string representation of column values.
If no value of
max_lines
is supplied then the height of the screen terminal is used to setmax_lines
. If the terminal height cannot be determined then the default will be determined using theastropy.conf.max_lines
configuration item. If a negative value ofmax_lines
is supplied then there is no line limit applied.- Parameters:
- max_linesint
Maximum lines of output (header + data rows)
- show_namebool
Include column name. Default is True.
- show_unitbool
Include a header row for unit. Default is False.
- show_dtypebool
Include column dtype. Default is False.
- htmlbool
Format the output as an HTML table. Default is False.
- Returns:
- lineslist
List of lines with header and formatted column values
- pprint(max_lines=None, show_name=True, show_unit=False, show_dtype=False)
Print a formatted string representation of column values.
If no value of
max_lines
is supplied then the height of the screen terminal is used to setmax_lines
. If the terminal height cannot be determined then the default will be determined using theastropy.conf.max_lines
configuration item. If a negative value ofmax_lines
is supplied then there is no line limit applied.- Parameters:
- max_linesint
Maximum number of values in output
- show_namebool
Include column name. Default is True.
- show_unitbool
Include a header row for unit. Default is False.
- show_dtypebool
Include column dtype. Default is True.
- class Row(table, index)
Bases:
object
A class to represent one row of a Table object.
A Row object is returned when a Table object is indexed with an integer or when iterating over a table:
>>> from astropy.table import Table >>> table = Table([(1, 2), (3, 4)], names=('a', 'b'), ... dtype=('int32', 'int32')) >>> row = table[1] >>> row <Row index=1> a b int32 int32 ----- ----- 2 4 >>> row['a'] 2 >>> row[1] 4
- __array__(dtype=None, copy=None)
Support converting Row to np.array via np.array(table).
Coercion to a different dtype via np.array(table, dtype) is not supported and will raise a ValueError.
If the parent table is masked then the mask information is dropped.
- __bytes__()
- __dict__ = mappingproxy({'__module__': 'astropy.table.row', '__doc__': "A class to represent one row of a Table object.\n\n A Row object is returned when a Table object is indexed with an integer\n or when iterating over a table::\n\n >>> from astropy.table import Table\n >>> table = Table([(1, 2), (3, 4)], names=('a', 'b'),\n ... dtype=('int32', 'int32'))\n >>> row = table[1]\n >>> row\n <Row index=1>\n a b\n int32 int32\n ----- -----\n 2 4\n >>> row['a']\n 2\n >>> row[1]\n 4\n ", '__init__': <function Row.__init__>, '__getitem__': <function Row.__getitem__>, '__setitem__': <function Row.__setitem__>, '_ipython_key_completions_': <function Row._ipython_key_completions_>, '__eq__': <function Row.__eq__>, '__ne__': <function Row.__ne__>, '__array__': <function Row.__array__>, '__len__': <function Row.__len__>, '__iter__': <function Row.__iter__>, 'get': <function Row.get>, 'keys': <function Row.keys>, 'values': <function Row.values>, 'table': <property object>, 'index': <property object>, 'as_void': <function Row.as_void>, 'meta': <property object>, 'columns': <property object>, 'colnames': <property object>, 'dtype': <property object>, '_base_repr_': <function Row._base_repr_>, '_repr_html_': <function Row._repr_html_>, '__repr__': <function Row.__repr__>, '__str__': <function Row.__str__>, '__bytes__': <function Row.__bytes__>, '__dict__': <attribute '__dict__' of 'Row' objects>, '__weakref__': <attribute '__weakref__' of 'Row' objects>, '__hash__': None, '__annotations__': {}})
- __doc__ = "A class to represent one row of a Table object.\n\n A Row object is returned when a Table object is indexed with an integer\n or when iterating over a table::\n\n >>> from astropy.table import Table\n >>> table = Table([(1, 2), (3, 4)], names=('a', 'b'),\n ... dtype=('int32', 'int32'))\n >>> row = table[1]\n >>> row\n <Row index=1>\n a b\n int32 int32\n ----- -----\n 2 4\n >>> row['a']\n 2\n >>> row[1]\n 4\n "
- __eq__(other)
Return self==value.
- __getitem__(item)
- __hash__ = None
- __init__(table, index)
- __iter__()
- __len__()
- __module__ = 'astropy.table.row'
- __ne__(other)
Return self!=value.
- __repr__()
Return repr(self).
- __setitem__(item, val)
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- _base_repr_(html=False)
Display row as a single-line table but with appropriate header line.
- _ipython_key_completions_()
- _repr_html_()
- as_void()
Returns a read-only copy of the row values in the form of np.void or np.ma.mvoid objects. This corresponds to the object types returned for row indexing of a pure numpy structured array or masked array. This method is slow and its use is discouraged when possible.
- Returns:
- void_row
numpy.void
ornumpy.ma.mvoid
Copy of row values.
numpy.void
if unmasked,numpy.ma.mvoid
else.
- void_row
- property colnames
- property columns
- property dtype
- get(key, default=None, /)
Return the value for key if key is in the columns, else default.
- Parameters:
- keystr, positional-only
The name of the column to look for.
- defaultobject, optional, positional-only
The value to return if the
key
is not among the columns.
- Returns:
- object
The value in the
key
column of the row if present,default
otherwise.
Examples
>>> from astropy.table import Table >>> t = Table({"a": [2, 3, 5], "b": [7, 11, 13]}) >>> t[0].get("a") 2 >>> t[1].get("b", 0) 11 >>> t[2].get("c", 0) 0
- property index
- keys()
- property meta
- property table
- values()
- class TableColumns(cols={})
Bases:
OrderedDict
OrderedDict subclass for a set of columns.
This class enhances item access to provide convenient access to columns by name or index, including slice access. It also handles renaming of columns.
The initialization argument
cols
can be a list ofColumn
objects or any structure that is valid for initializing a Python dict. This includes a dict, list of (key, val) tuples or [key, val] lists, etc.- Parameters:
- colsdict, list, tuple; optional
Column objects as data structure that can init dict (see above)
- __delitem__(name)
Delete self[key].
- __doc__ = 'OrderedDict subclass for a set of columns.\n\n This class enhances item access to provide convenient access to columns\n by name or index, including slice access. It also handles renaming\n of columns.\n\n The initialization argument ``cols`` can be a list of ``Column`` objects\n or any structure that is valid for initializing a Python dict. This\n includes a dict, list of (key, val) tuples or [key, val] lists, etc.\n\n Parameters\n ----------\n cols : dict, list, tuple; optional\n Column objects as data structure that can init dict (see above)\n '
- __getitem__(item)
Get items from a TableColumns object.
tc = TableColumns(cols=[Column(name='a'), Column(name='b'), Column(name='c')]) tc['a'] # Column('a') tc[1] # Column('b') tc['a', 'b'] # <TableColumns names=('a', 'b')> tc[1:3] # <TableColumns names=('b', 'c')>
- __init__(cols={})
- __module__ = 'astropy.table.table'
- __repr__()
Return repr(self).
- __setitem__(item, value, validated=False)
Set item in this dict instance, but do not allow directly replacing an existing column unless it is already validated (and thus is certain to not corrupt the table).
NOTE: it is easily possible to corrupt a table by directly adding a new key to the TableColumns attribute of a Table, e.g.
t.columns['jane'] = 'doe'
.
- _rename_column(name, new_name)
- isinstance(cls)
Return a list of columns which are instances of the specified classes.
- Parameters:
- clsclass or tuple thereof
Column class (including mixin) or tuple of Column classes.
- Returns:
- col_listlist of Column
List of Column objects which are instances of given classes.
- not_isinstance(cls)
Return a list of columns which are not instances of the specified classes.
- Parameters:
- clsclass or tuple thereof
Column class (including mixin) or tuple of Column classes.
- Returns:
- col_listlist of Column
List of Column objects which are not instances of given classes.
- setdefault(key, default)
Deprecated since version 6.1: The t.columns.setdefault() function is deprecated and may be removed in a future version. Use t.setdefault() instead.
- update(*args, **kwargs)
Deprecated since version 6.1: The t.columns.update() function is deprecated and may be removed in a future version. Use t.update() instead.
- class TableFormatter
Bases:
object
- __dict__ = mappingproxy({'__module__': 'astropy.table.pprint', '_get_pprint_size': <staticmethod(<function TableFormatter._get_pprint_size>)>, '_pformat_col': <function TableFormatter._pformat_col>, '_name_and_structure': <function TableFormatter._name_and_structure>, '_pformat_col_iter': <function TableFormatter._pformat_col_iter>, '_pformat_table': <function TableFormatter._pformat_table>, '_more_tabcol': <function TableFormatter._more_tabcol>, '__dict__': <attribute '__dict__' of 'TableFormatter' objects>, '__weakref__': <attribute '__weakref__' of 'TableFormatter' objects>, '__doc__': None, '__annotations__': {}})
- __doc__ = None
- __module__ = 'astropy.table.pprint'
- __weakref__
list of weak references to the object (if defined)
- static _get_pprint_size(max_lines=None, max_width=None)
Get the output size (number of lines and character width) for Column and Table pformat/pprint methods.
If no value of
max_lines
is supplied then the height of the screen terminal is used to setmax_lines
. If the terminal height cannot be determined then the default will be determined using theastropy.table.conf.max_lines
configuration item. If a negative value ofmax_lines
is supplied then there is no line limit applied.The same applies for max_width except the configuration item is
astropy.table.conf.max_width
.- Parameters:
- max_linesint or None
Maximum lines of output (header + data rows)
- max_widthint or None
Maximum width (characters) output
- Returns:
- max_lines, max_widthint
- _more_tabcol(tabcol, max_lines=None, max_width=None, show_name=True, show_unit=None, show_dtype=False)
Interactive “more” of a table or column.
- Parameters:
- max_linesint or None
Maximum number of rows to output
- max_widthint or None
Maximum character width of output
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- show_dtypebool
Include a header row for column dtypes. Default is False.
- _name_and_structure(name, dtype, sep=' ')
Format a column name, including a possible structure.
Normally, just returns the name, but if it has a structured dtype, will add the parts in between square brackets. E.g., “name [f0, f1]” or “name [f0[sf0, sf1], f1]”.
- _pformat_col(col, max_lines=None, show_name=True, show_unit=None, show_dtype=False, show_length=None, html=False, align=None)
Return a list of formatted string representation of column values.
- Parameters:
- max_linesint
Maximum lines of output (header + data rows)
- show_namebool
Include column name. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- show_dtypebool
Include column dtype. Default is False.
- show_lengthbool
Include column length at end. Default is to show this only if the column is not shown completely.
- htmlbool
Output column as HTML
- alignstr
Left/right alignment of columns. Default is ‘>’ (right) for all columns. Other allowed values are ‘<’, ‘^’, and ‘0=’ for left, centered, and 0-padded, respectively.
- Returns:
- lineslist
List of lines with formatted column values
- outsdict
Dict which is used to pass back additional values defined within the iterator.
- _pformat_col_iter(col, max_lines, show_name, show_unit, outs, show_dtype=False, show_length=None)
Iterator which yields formatted string representation of column values.
- Parameters:
- max_linesint
Maximum lines of output (header + data rows)
- show_namebool
Include column name. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- outsdict
Must be a dict which is used to pass back additional values defined within the iterator.
- show_dtypebool
Include column dtype. Default is False.
- show_lengthbool
Include column length at end. Default is to show this only if the column is not shown completely.
- _pformat_table(table, max_lines=None, max_width=None, show_name=True, show_unit=None, show_dtype=False, html=False, tableid=None, tableclass=None, align=None)
Return a list of lines for the formatted string representation of the table.
- Parameters:
- max_linesint or None
Maximum number of rows to output
- max_widthint or None
Maximum character width of output
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- show_dtypebool
Include a header row for column dtypes. Default is to False.
- htmlbool
Format the output as an HTML table. Default is False.
- tableidstr or None
An ID tag for the table; only used if html is set. Default is “table{id}”, where id is the unique integer id of the table object, id(table)
- tableclassstr or list of str or None
CSS classes for the table; only used if html is set. Default is none
- alignstr or list or tuple
Left/right alignment of columns. Default is ‘>’ (right) for all columns. Other allowed values are ‘<’, ‘^’, and ‘0=’ for left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.
- Returns:
- rowslist
Formatted table as a list of strings
- outsdict
Dict which is used to pass back additional values defined within the iterator.
- __array__(dtype=None, copy=None)
Support converting Table to np.array via np.array(table).
Coercion to a different dtype via np.array(table, dtype) is not supported and will raise a ValueError.
- __bytes__()
- __copy__()
- __deepcopy__(memo=None)
- __delitem__(item)
- __dict__ = mappingproxy({'__module__': 'astropy.table.table', '__doc__': 'A class to represent tables of heterogeneous data.\n\n `~astropy.table.Table` provides a class for heterogeneous tabular data.\n A key enhancement provided by the `~astropy.table.Table` class over\n e.g. a `numpy` structured array is the ability to easily modify the\n structure of the table by adding or removing columns, or adding new\n rows of data. In addition table and column metadata are fully supported.\n\n `~astropy.table.Table` differs from `~astropy.nddata.NDData` by the\n assumption that the input data consists of columns of homogeneous data,\n where each column has a unique identifier and may contain additional\n metadata such as the data unit, format, and description.\n\n See also: https://docs.astropy.org/en/stable/table/\n\n Parameters\n ----------\n data : numpy ndarray, dict, list, table-like object, optional\n Data to initialize table.\n masked : bool, optional\n Specify whether the table is masked.\n names : list, optional\n Specify column names.\n dtype : list, optional\n Specify column data types.\n meta : dict, optional\n Metadata associated with the table.\n copy : bool, optional\n Copy the input column data and make a deep copy of the input meta.\n Default is True.\n rows : numpy ndarray, list of list, optional\n Row-oriented data for table instead of ``data`` argument.\n copy_indices : bool, optional\n Copy any indices in the input data. Default is True.\n units : list, dict, optional\n List or dict of units to apply to columns.\n descriptions : list, dict, optional\n List or dict of descriptions to apply to columns.\n **kwargs : dict, optional\n Additional keyword args when converting table-like object.\n ', 'meta': <astropy.utils.metadata.core.MetaData object>, 'Row': <class 'astropy.table.row.Row'>, 'Column': <class 'astropy.table.column.Column'>, 'MaskedColumn': <class 'astropy.table.column.MaskedColumn'>, 'TableColumns': <class 'astropy.table.table.TableColumns'>, 'TableFormatter': <class 'astropy.table.pprint.TableFormatter'>, 'read': <astropy.io.registry.interface.UnifiedReadWriteMethod object>, 'write': <astropy.io.registry.interface.UnifiedReadWriteMethod object>, 'pprint_exclude_names': <PprintIncludeExclude name=pprint_exclude_names default=None>, 'pprint_include_names': <PprintIncludeExclude name=pprint_include_names default=None>, 'as_array': <function Table.as_array>, '__init__': <function Table.__init__>, '_set_column_attribute': <function Table._set_column_attribute>, '__getstate__': <function Table.__getstate__>, '__setstate__': <function Table.__setstate__>, 'mask': <property object>, '_mask': <property object>, 'filled': <function Table.filled>, 'indices': <property object>, 'loc': <property object>, 'loc_indices': <property object>, 'iloc': <property object>, 'add_index': <function Table.add_index>, 'remove_indices': <function Table.remove_indices>, 'index_mode': <function Table.index_mode>, '__array__': <function Table.__array__>, '_check_names_dtype': <function Table._check_names_dtype>, '_init_from_list_of_dicts': <function Table._init_from_list_of_dicts>, '_init_from_list': <function Table._init_from_list>, '_convert_data_to_col': <function Table._convert_data_to_col>, '_init_from_ndarray': <function Table._init_from_ndarray>, '_init_from_dict': <function Table._init_from_dict>, '_get_col_cls_for_table': <function Table._get_col_cls_for_table>, '_convert_col_for_table': <function Table._convert_col_for_table>, '_init_from_cols': <function Table._init_from_cols>, '_new_from_slice': <function Table._new_from_slice>, '_make_table_from_cols': <staticmethod(<function Table._make_table_from_cols>)>, '_set_col_parent_table_and_mask': <function Table._set_col_parent_table_and_mask>, 'itercols': <function Table.itercols>, '_base_repr_': <function Table._base_repr_>, '_repr_html_': <function Table._repr_html_>, '__repr__': <function Table.__repr__>, '__str__': <function Table.__str__>, '__bytes__': <function Table.__bytes__>, 'has_mixin_columns': <property object>, 'has_masked_columns': <property object>, 'has_masked_values': <property object>, '_is_mixin_for_table': <function Table._is_mixin_for_table>, 'pprint': <function Table.pprint>, 'pprint_all': <function Table.pprint_all>, '_make_index_row_display_table': <function Table._make_index_row_display_table>, 'show_in_notebook': <function Table.show_in_notebook>, 'show_in_browser': <function Table.show_in_browser>, 'pformat': <function Table.pformat>, 'pformat_all': <function Table.pformat_all>, 'more': <function Table.more>, '__getitem__': <function Table.__getitem__>, '__setitem__': <function Table.__setitem__>, '__delitem__': <function Table.__delitem__>, '_ipython_key_completions_': <function Table._ipython_key_completions_>, 'field': <function Table.field>, 'masked': <property object>, '_set_masked': <function Table._set_masked>, 'ColumnClass': <property object>, 'dtype': <property object>, 'colnames': <property object>, '_is_list_or_tuple_of_str': <staticmethod(<function Table._is_list_or_tuple_of_str>)>, 'keys': <function Table.keys>, 'values': <function Table.values>, 'items': <function Table.items>, '__len__': <function Table.__len__>, '__or__': <function Table.__or__>, '__ior__': <function Table.__ior__>, 'index_column': <function Table.index_column>, 'add_column': <function Table.add_column>, 'add_columns': <function Table.add_columns>, '_replace_column_warnings': <function Table._replace_column_warnings>, 'replace_column': <function Table.replace_column>, 'remove_row': <function Table.remove_row>, 'remove_rows': <function Table.remove_rows>, 'iterrows': <function Table.iterrows>, '_set_of_names_in_colnames': <function Table._set_of_names_in_colnames>, 'remove_column': <function Table.remove_column>, 'remove_columns': <function Table.remove_columns>, '_convert_string_dtype': <function Table._convert_string_dtype>, 'convert_bytestring_to_unicode': <function Table.convert_bytestring_to_unicode>, 'convert_unicode_to_bytestring': <function Table.convert_unicode_to_bytestring>, 'keep_columns': <function Table.keep_columns>, 'rename_column': <function Table.rename_column>, 'rename_columns': <function Table.rename_columns>, '_set_row': <function Table._set_row>, 'add_row': <function Table.add_row>, 'insert_row': <function Table.insert_row>, '_replace_cols': <function Table._replace_cols>, 'setdefault': <function Table.setdefault>, 'update': <function Table.update>, 'argsort': <function Table.argsort>, 'sort': <function Table.sort>, 'reverse': <function Table.reverse>, 'round': <function Table.round>, 'copy': <function Table.copy>, '__deepcopy__': <function Table.__deepcopy__>, '__copy__': <function Table.__copy__>, '__eq__': <function Table.__eq__>, '__ne__': <function Table.__ne__>, '_rows_equal': <function Table._rows_equal>, 'values_equal': <function Table.values_equal>, 'groups': <property object>, 'group_by': <function Table.group_by>, 'to_pandas': <function Table.to_pandas>, 'from_pandas': <classmethod(<function Table.from_pandas>)>, 'info': <astropy.table.info.TableInfo object>, '__dict__': <attribute '__dict__' of 'Table' objects>, '__weakref__': <attribute '__weakref__' of 'Table' objects>, '__hash__': None, '__annotations__': {}})
- __doc__ = 'A class to represent tables of heterogeneous data.\n\n `~astropy.table.Table` provides a class for heterogeneous tabular data.\n A key enhancement provided by the `~astropy.table.Table` class over\n e.g. a `numpy` structured array is the ability to easily modify the\n structure of the table by adding or removing columns, or adding new\n rows of data. In addition table and column metadata are fully supported.\n\n `~astropy.table.Table` differs from `~astropy.nddata.NDData` by the\n assumption that the input data consists of columns of homogeneous data,\n where each column has a unique identifier and may contain additional\n metadata such as the data unit, format, and description.\n\n See also: https://docs.astropy.org/en/stable/table/\n\n Parameters\n ----------\n data : numpy ndarray, dict, list, table-like object, optional\n Data to initialize table.\n masked : bool, optional\n Specify whether the table is masked.\n names : list, optional\n Specify column names.\n dtype : list, optional\n Specify column data types.\n meta : dict, optional\n Metadata associated with the table.\n copy : bool, optional\n Copy the input column data and make a deep copy of the input meta.\n Default is True.\n rows : numpy ndarray, list of list, optional\n Row-oriented data for table instead of ``data`` argument.\n copy_indices : bool, optional\n Copy any indices in the input data. Default is True.\n units : list, dict, optional\n List or dict of units to apply to columns.\n descriptions : list, dict, optional\n List or dict of descriptions to apply to columns.\n **kwargs : dict, optional\n Additional keyword args when converting table-like object.\n '
- __eq__(other)
Return self==value.
- __getitem__(item)
- __getstate__()
- __hash__ = None
- __init__(data=None, masked=False, names=None, dtype=None, meta=None, copy=True, rows=None, copy_indices=True, units=None, descriptions=None, **kwargs)
- __ior__(other)
- __len__()
- __module__ = 'astropy.table.table'
- __ne__(other)
Return self!=value.
- __or__(other)
Return self|value.
- __repr__()
Return repr(self).
- __setitem__(item, value)
- __setstate__(state)
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- _base_repr_(html=False, descr_vals=None, max_width=None, tableid=None, show_dtype=True, max_lines=None, tableclass=None)
- _check_names_dtype(names, dtype, n_cols)
Make sure that names and dtype are both iterable and have the same length as data.
- _convert_col_for_table(col)
Make sure that all Column objects have correct base class for this type of Table. For a base Table this most commonly means setting to MaskedColumn if the table is masked. Table subclasses like QTable override this method.
- _convert_data_to_col(data, copy=True, default_name=None, dtype=None, name=None)
Convert any allowed sequence data
col
to a column object that can be used directly in the self.columns dict. This could be a Column, MaskedColumn, or mixin column.The final column name is determined by:
name or data.info.name or def_name
If
data
has noinfo
thenname = name or def_name
.The behavior of
copy
for Column objects is: - copy=True: new class instance with a copy of data and deep copy of meta - copy=False: new class instance with same data and a key-only copy of metaFor mixin columns: - copy=True: new class instance with copy of data and deep copy of meta - copy=False: original instance (no copy at all)
- Parameters:
- dataobject (column-like sequence)
Input column data
- copybool
Make a copy
- default_namestr
Default name
- dtypenp.dtype or None
Data dtype
- namestr or None
Column name
- Returns:
- colColumn, MaskedColumn, mixin-column type
Object that can be used as a column in self
- _convert_string_dtype(in_kind, out_kind, encode_decode_func)
Convert string-like columns to/from bytestring and unicode (internal only).
- Parameters:
- in_kindstr
Input dtype.kind
- out_kindstr
Output dtype.kind
- _get_col_cls_for_table(col)
Get the correct column class to use for upgrading any Column-like object.
For a masked table, ensure any Column-like object is a subclass of the table MaskedColumn.
For unmasked table, ensure any MaskedColumn-like object is a subclass of the table MaskedColumn. If not a MaskedColumn, then ensure that any Column-like object is a subclass of the table Column.
- _init_from_cols(cols)
Initialize table from a list of Column or mixin objects.
- _init_from_dict(data, names, dtype, n_cols, copy)
Initialize table from a dictionary of columns.
- _init_from_list(data, names, dtype, n_cols, copy)
Initialize table from a list of column data. A column can be a Column object, np.ndarray, mixin, or any other iterable object.
- _init_from_list_of_dicts(data, names, dtype, n_cols, copy)
Initialize table from a list of dictionaries representing rows.
- _init_from_ndarray(data, names, dtype, n_cols, copy)
Initialize table from an ndarray structured array.
- _ipython_key_completions_()
- static _is_list_or_tuple_of_str(names)
Check that
names
is a tuple or list of strings.
- _is_mixin_for_table(col)
Determine if
col
should be added to the table directly as a mixin column.
- _make_index_row_display_table(index_row_name)
- static _make_table_from_cols(table, cols, verify=True, names=None)
Make
table
in-place so that it represents the given list ofcols
.
- property _mask
This is needed so that comparison of a masked Table and a MaskedArray works. The requirement comes from numpy.ma.core so don’t remove this property.
- _new_from_slice(slice_)
Create a new table as a referenced slice from self.
- _replace_cols(columns)
- _replace_column_warnings(name, col)
Same as replace_column but issues warnings under various circumstances.
- _repr_html_()
- _rows_equal(other)
Row-wise comparison of table with any other object.
This is actual implementation for __eq__.
Returns a 1-D boolean numpy array showing result of row-wise comparison, or a bool (False) in cases where comparison isn’t possible (uncomparable dtypes or unbroadcastable shapes). Intended to follow legacy numpy’s elementwise comparison rules.
This is the same as the
==
comparison for tables.- Parameters:
- otherTable or DataFrame or ndarray
An object to compare with table
Examples
Comparing one Table with other:
>>> t1 = Table([[1,2],[4,5],[7,8]], names=('a','b','c')) >>> t2 = Table([[1,2],[4,5],[7,8]], names=('a','b','c')) >>> t1._rows_equal(t2) array([ True, True])
- _set_col_parent_table_and_mask(col)
Set
col.parent_table = self
and forcecol
to havemask
attribute if the table is masked andcol.mask
does not exist.
- _set_column_attribute(attr, values)
Set
attr
for columns tovalues
, which can be either a dict (keyed by column name) or a dict of name: value pairs. This is used for handling theunits
anddescriptions
kwargs to__init__
.
- _set_masked(masked)
Set the table masked property.
- Parameters:
- maskedbool
State of table masking (True or False)
- _set_of_names_in_colnames(names)
Return
names
as a set if valid, or raise a KeyError.names
is valid if all elements in it are inself.colnames
. Ifnames
is a string then it is interpreted as a single column name.
- _set_row(idx, colnames, vals)
- add_column(col, index=None, name=None, rename_duplicate=False, copy=True, default_name=None)
Add a new column to the table using
col
as input. Ifindex
is supplied then insert column beforeindex
position in the list of columns, otherwise append column to the end of the list.The
col
input can be any data object which is acceptable as a ~astropy.table.Table column object or can be converted. This includes mixin columns and scalar or length=1 objects which get broadcast to match the table length.To add several columns at once use
add_columns()
or simply calladd_column()
for each one. There is very little performance difference in the two approaches.- Parameters:
- colobject
Data object for the new column
- indexint or None
Insert column before this position or at end (default).
- namestr
Column name
- rename_duplicatebool
Uniquify column name if it already exist. Default is False.
- copybool
Make a copy of the new column. Default is True.
- default_namestr or None
Name to use if both
name
andcol.info.name
are not available. Defaults tocol{number_of_columns}
.
Examples
Create a table with two columns ‘a’ and ‘b’, then create a third column ‘c’ and append it to the end of the table:
>>> t = Table([[1, 2], [0.1, 0.2]], names=('a', 'b')) >>> col_c = Column(name='c', data=['x', 'y']) >>> t.add_column(col_c) >>> print(t) a b c --- --- --- 1 0.1 x 2 0.2 y
Add column ‘d’ at position 1. Note that the column is inserted before the given index:
>>> t.add_column(['a', 'b'], name='d', index=1) >>> print(t) a d b c --- --- --- --- 1 a 0.1 x 2 b 0.2 y
Add second column named ‘b’ with rename_duplicate:
>>> t = Table([[1, 2], [0.1, 0.2]], names=('a', 'b')) >>> t.add_column(1.1, name='b', rename_duplicate=True) >>> print(t) a b b_1 --- --- --- 1 0.1 1.1 2 0.2 1.1
Add an unnamed column or mixin object in the table using a default name or by specifying an explicit name with
name
. Name can also be overridden:>>> t = Table([[1, 2], [0.1, 0.2]], names=('a', 'b')) >>> t.add_column(['a', 'b']) >>> t.add_column(col_c, name='d') >>> print(t) a b col2 d --- --- ---- --- 1 0.1 a x 2 0.2 b y
- add_columns(cols, indexes=None, names=None, copy=True, rename_duplicate=False)
Add a list of new columns the table using
cols
data objects. If a corresponding list ofindexes
is supplied then insert column before eachindex
position in the original list of columns, otherwise append columns to the end of the list.The
cols
input can include any data objects which are acceptable as ~astropy.table.Table column objects or can be converted. This includes mixin columns and scalar or length=1 objects which get broadcast to match the table length.From a performance perspective there is little difference between calling this method once or looping over the new columns and calling
add_column()
for each column.- Parameters:
- colslist of object
List of data objects for the new columns
- indexeslist of int or None
Insert column before this position or at end (default).
- nameslist of str
Column names
- copybool
Make a copy of the new columns. Default is True.
- rename_duplicatebool
Uniquify new column names if they duplicate the existing ones. Default is False.
See also
Examples
Create a table with two columns ‘a’ and ‘b’, then create columns ‘c’ and ‘d’ and append them to the end of the table:
>>> t = Table([[1, 2], [0.1, 0.2]], names=('a', 'b')) >>> col_c = Column(name='c', data=['x', 'y']) >>> col_d = Column(name='d', data=['u', 'v']) >>> t.add_columns([col_c, col_d]) >>> print(t) a b c d --- --- --- --- 1 0.1 x u 2 0.2 y v
Add column ‘c’ at position 0 and column ‘d’ at position 1. Note that the columns are inserted before the given position:
>>> t = Table([[1, 2], [0.1, 0.2]], names=('a', 'b')) >>> t.add_columns([['x', 'y'], ['u', 'v']], names=['c', 'd'], ... indexes=[0, 1]) >>> print(t) c a d b --- --- --- --- x 1 u 0.1 y 2 v 0.2
Add second column ‘b’ and column ‘c’ with
rename_duplicate
:>>> t = Table([[1, 2], [0.1, 0.2]], names=('a', 'b')) >>> t.add_columns([[1.1, 1.2], ['x', 'y']], names=('b', 'c'), ... rename_duplicate=True) >>> print(t) a b b_1 c --- --- --- --- 1 0.1 1.1 x 2 0.2 1.2 y
Add unnamed columns or mixin objects in the table using default names or by specifying explicit names with
names
. Names can also be overridden:>>> t = Table() >>> col_b = Column(name='b', data=['u', 'v']) >>> t.add_columns([[1, 2], col_b]) >>> t.add_columns([[3, 4], col_b], names=['c', 'd']) >>> print(t) col0 b c d ---- --- --- --- 1 u 3 u 2 v 4 v
- add_index(colnames, engine=None, unique=False)
Insert a new index among one or more columns. If there are no indices, make this index the primary table index.
- Parameters:
- colnamesstr or list
List of column names (or a single column name) to index
- enginetype or None
Indexing engine class to use, either ~astropy.table.SortedArray, ~astropy.table.BST, or ~astropy.table.SCEngine. If the supplied argument is None (by default), use ~astropy.table.SortedArray.
- uniquebool
Whether the values of the index must be unique. Default is False.
- add_row(vals=None, mask=None)
Add a new row to the end of the table.
The
vals
argument can be:- sequence (e.g. tuple or list)
Column values in the same order as table columns.
- mapping (e.g. dict)
Keys corresponding to column names. Missing values will be filled with np.zeros for the column dtype.
- None
All values filled with np.zeros for the column dtype.
This method requires that the Table object “owns” the underlying array data. In particular one cannot add a row to a Table that was initialized with copy=False from an existing array.
The
mask
attribute should give (if desired) the mask for the values. The type of the mask should match that of the values, i.e. ifvals
is an iterable, thenmask
should also be an iterable with the same length, and ifvals
is a mapping, thenmask
should be a dictionary.- Parameters:
- valstuple, list, dict or None
Use the specified values in the new row
- masktuple, list, dict or None
Use the specified mask values in the new row
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table([[1,2],[4,5],[7,8]], names=('a','b','c')) >>> print(t) a b c --- --- --- 1 4 7 2 5 8
Adding a new row with entries ‘3’ in ‘a’, ‘6’ in ‘b’ and ‘9’ in ‘c’:
>>> t.add_row([3,6,9]) >>> print(t) a b c --- --- --- 1 4 7 2 5 8 3 6 9
- argsort(keys=None, kind=None, reverse=False)
Return the indices which would sort the table according to one or more key columns. This simply calls the numpy.argsort function on the table with the
order
parameter set tokeys
.- Parameters:
- keysstr or list of str
The column name(s) to order the table by
- kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional
Sorting algorithm used by
numpy.argsort
.- reversebool
Sort in reverse order (default=False)
- Returns:
- index_arrayndarray, int
Array of indices that sorts the table by the specified key column(s).
- as_array(keep_byteorder=False, names=None)
Return a new copy of the table in the form of a structured np.ndarray or np.ma.MaskedArray object (as appropriate).
- Parameters:
- keep_byteorderbool, optional
By default the returned array has all columns in native byte order. However, if this option is True this preserves the byte order of all columns (if any are non-native).
- nameslist, optional:
List of column names to include for returned structured array. Default is to include all table columns.
- Returns:
- table_arrayarray or ~numpy.ma.MaskedArray
Copy of table as a numpy structured array. ndarray for unmasked or ~numpy.ma.MaskedArray for masked.
- property colnames
- convert_bytestring_to_unicode()
Convert bytestring columns (dtype.kind=’S’) to unicode (dtype.kind=’U’) using UTF-8 encoding.
Internally this changes string columns to represent each character in the string with a 4-byte UCS-4 equivalent, so it is inefficient for memory but allows scripts to manipulate string arrays with natural syntax.
- convert_unicode_to_bytestring()
Convert unicode columns (dtype.kind=’U’) to bytestring (dtype.kind=’S’) using UTF-8 encoding.
When exporting a unicode string array to a file, it may be desirable to encode unicode columns as bytestrings.
- copy(copy_data=True)
Return a copy of the table.
- Parameters:
- copy_databool
If True (the default), copy the underlying data array and make a deep copy of the
meta
attribute. Otherwise, use the same data array and make a shallow (key-only) copy ofmeta
.
- property dtype
- field(item)
Return column[item] for recarray compatibility.
- filled(fill_value=None)
Return copy of self, with masked values filled.
If input
fill_value
supplied then that value is used for all masked entries in the table. Otherwise the individualfill_value
defined for each table column is used.- Parameters:
- fill_valuestr
If supplied, this
fill_value
is used for all masked entries in the entire table.
- Returns:
- filled_table~astropy.table.Table
New table with masked values filled
- classmethod from_pandas(dataframe, index=False, units=None)
Create a ~astropy.table.Table from a
pandas.DataFrame
instance.In addition to converting generic numeric or string columns, this supports conversion of pandas Date and Time delta columns to ~astropy.time.Time and ~astropy.time.TimeDelta columns, respectively.
- Parameters:
- dataframe
pandas.DataFrame
A pandas
pandas.DataFrame
instance- indexbool
Include the index column in the returned table (default=False)
- units: dict
A dict mapping column names to a ~astropy.units.Unit. The columns will have the specified unit in the Table.
- dataframe
- Returns:
- table~astropy.table.Table
A ~astropy.table.Table (or subclass) instance
- Raises:
- ImportError
If pandas is not installed
Examples
Here we convert a
pandas.DataFrame
instance to a ~astropy.table.QTable.>>> import numpy as np >>> import pandas as pd >>> from astropy.table import QTable
>>> time = pd.Series(['1998-01-01', '2002-01-01'], dtype='datetime64[ns]') >>> dt = pd.Series(np.array([1, 300], dtype='timedelta64[s]')) >>> df = pd.DataFrame({'time': time}) >>> df['dt'] = dt >>> df['x'] = [3., 4.] >>> with pd.option_context('display.max_columns', 20): ... print(df) time dt x 0 1998-01-01 0 days 00:00:01 3.0 1 2002-01-01 0 days 00:05:00 4.0
>>> QTable.from_pandas(df) <QTable length=2> time dt x Time TimeDelta float64 ----------------------- --------- ------- 1998-01-01T00:00:00.000 1.0 3.0 2002-01-01T00:00:00.000 300.0 4.0
- group_by(keys)
Group this table by the specified
keys
.This effectively splits the table into groups which correspond to unique values of the
keys
grouping object. The output is a new ~astropy.table.TableGroups which contains a copy of this table but sorted by row according tokeys
.The
keys
input to group_by can be specified in different ways:String or list of strings corresponding to table column name(s)
Numpy array (homogeneous or structured) with same length as this table
~astropy.table.Table with same length as this table
- Parameters:
- keysstr, list of str, numpy array, or ~astropy.table.Table
Key grouping object
- Returns:
- out~astropy.table.Table
New table with groups set
- property groups
- property has_masked_columns
True if table has any
MaskedColumn
columns.This does not check for mixin columns that may have masked values, use the
has_masked_values
property in that case.
- property has_masked_values
True if column in the table has values which are masked.
This may be relatively slow for large tables as it requires checking the mask values of each column.
- property has_mixin_columns
True if table has any mixin columns (defined as columns that are not Column subclasses).
- property iloc
Return a TableILoc object that can be used for retrieving indexed rows in the order they appear in the index.
- index_column(name)
Return the positional index of column
name
.- Parameters:
- namestr
column name
- Returns:
- indexint
Positional index of column
name
.
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> print(t) a b c --- --- --- 1 0.1 x 2 0.2 y 3 0.3 z
Get index of column ‘b’ of the table:
>>> t.index_column('b') 1
- index_mode(mode)
Return a context manager for an indexing mode.
- Parameters:
- modestr
Either ‘freeze’, ‘copy_on_getitem’, or ‘discard_on_copy’. In ‘discard_on_copy’ mode, indices are not copied whenever columns or tables are copied. In ‘freeze’ mode, indices are not modified whenever columns are modified; at the exit of the context, indices refresh themselves based on column values. This mode is intended for scenarios in which one intends to make many additions or modifications in an indexed column. In ‘copy_on_getitem’ mode, indices are copied when taking column slices as well as table slices, so col[i0:i1] will preserve indices.
- property indices
Return the indices associated with columns of the table as a TableIndices object.
- info
- insert_row(index, vals=None, mask=None)
Add a new row before the given
index
position in the table.The
vals
argument can be:- sequence (e.g. tuple or list)
Column values in the same order as table columns.
- mapping (e.g. dict)
Keys corresponding to column names. Missing values will be filled with np.zeros for the column dtype.
- None
All values filled with np.zeros for the column dtype.
The
mask
attribute should give (if desired) the mask for the values. The type of the mask should match that of the values, i.e. ifvals
is an iterable, thenmask
should also be an iterable with the same length, and ifvals
is a mapping, thenmask
should be a dictionary.- Parameters:
- valstuple, list, dict or None
Use the specified values in the new row
- masktuple, list, dict or None
Use the specified mask values in the new row
- items()
- itercols()
Iterate over the columns of this table.
Examples
To iterate over the columns of a table:
>>> t = Table([[1], [2]]) >>> for col in t.itercols(): ... print(col) col0 ---- 1 col1 ---- 2
Using
itercols()
is similar tofor col in t.columns.values()
but is syntactically preferred.
- iterrows(*names)
Iterate over rows of table returning a tuple of values for each row.
This method is especially useful when only a subset of columns are needed.
The
iterrows
method can be substantially faster than using the standard Table row iteration (e.g.for row in tbl:
), since that returns a new~astropy.table.Row
object for each row and accessing a column in that row (e.g.row['col0']
) is slower than tuple access.- Parameters:
- nameslist
List of column names (default to all columns if no names provided)
- Returns:
- rowsiterable
Iterator returns tuples of row values
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table({'a': [1, 2, 3], ... 'b': [1.0, 2.5, 3.0], ... 'c': ['x', 'y', 'z']})
To iterate row-wise using column names:
>>> for a, c in t.iterrows('a', 'c'): ... print(a, c) 1 x 2 y 3 z
- keep_columns(names)
Keep only the columns specified (remove the others).
- Parameters:
- namesstr or iterable of str
The columns to keep. All other columns will be removed.
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table([[1, 2, 3],[0.1, 0.2, 0.3],['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> print(t) a b c --- --- --- 1 0.1 x 2 0.2 y 3 0.3 z
Keep only column ‘a’ of the table:
>>> t.keep_columns('a') >>> print(t) a --- 1 2 3
Keep columns ‘a’ and ‘c’ of the table:
>>> t = Table([[1, 2, 3],[0.1, 0.2, 0.3],['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> t.keep_columns(['a', 'c']) >>> print(t) a c --- --- 1 x 2 y 3 z
- keys()
- property loc
Return a TableLoc object that can be used for retrieving rows by index in a given data range. Note that both loc and iloc work only with single-column indices.
- property loc_indices
Return a TableLocIndices object that can be used for retrieving the row indices corresponding to given table index key value or values.
- property mask
- property masked
- meta = None
- more(max_lines=None, max_width=None, show_name=True, show_unit=None, show_dtype=False)
Interactively browse table with a paging interface.
Supported keys:
f, <space> : forward one page b : back one page r : refresh same page n : next row p : previous row < : go to beginning > : go to end q : quit browsing h : print this help
- Parameters:
- max_linesint
Maximum number of lines in table output
- max_widthint or None
Maximum character width of output
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- show_dtypebool
Include a header row for column dtypes. Default is False.
- pformat(max_lines=None, max_width=None, show_name=True, show_unit=None, show_dtype=False, html=False, tableid=None, align=None, tableclass=None)
- Return a list of lines for the formatted string representation of
the table.
If no value of
max_lines
is supplied then the height of the screen terminal is used to setmax_lines
. If the terminal height cannot be determined then the default is taken from the configuration itemastropy.conf.max_lines
. If a negative value ofmax_lines
is supplied then there is no line limit applied.The same applies for
max_width
except the configuration item isastropy.conf.max_width
.
- Parameters:
- max_linesint or None
Maximum number of rows to output
- max_widthint or None
Maximum character width of output
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- show_dtypebool
Include a header row for column dtypes. Default is True.
- htmlbool
Format the output as an HTML table. Default is False.
- tableidstr or None
An ID tag for the table; only used if html is set. Default is “table{id}”, where id is the unique integer id of the table object, id(self)
- alignstr or list or tuple or None
Left/right alignment of columns. Default is right (None) for all columns. Other allowed values are ‘>’, ‘<’, ‘^’, and ‘0=’ for right, left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.
- tableclassstr or list of str or None
CSS classes for the table; only used if html is set. Default is None.
- Returns:
- lineslist
Formatted table as a list of strings.
- pformat_all(max_lines=-1, max_width=-1, show_name=True, show_unit=None, show_dtype=False, html=False, tableid=None, align=None, tableclass=None)
- Return a list of lines for the formatted string representation of
the entire table.
If no value of
max_lines
is supplied then the height of the screen terminal is used to setmax_lines
. If the terminal height cannot be determined then the default is taken from the configuration itemastropy.conf.max_lines
. If a negative value ofmax_lines
is supplied then there is no line limit applied.The same applies for
max_width
except the configuration item isastropy.conf.max_width
.
- Parameters:
- max_linesint or None
Maximum number of rows to output
- max_widthint or None
Maximum character width of output
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- show_dtypebool
Include a header row for column dtypes. Default is True.
- htmlbool
Format the output as an HTML table. Default is False.
- tableidstr or None
An ID tag for the table; only used if html is set. Default is “table{id}”, where id is the unique integer id of the table object, id(self)
- alignstr or list or tuple or None
Left/right alignment of columns. Default is right (None) for all columns. Other allowed values are ‘>’, ‘<’, ‘^’, and ‘0=’ for right, left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.
- tableclassstr or list of str or None
CSS classes for the table; only used if html is set. Default is None.
- Returns:
- lineslist
Formatted table as a list of strings.
- pprint(max_lines=None, max_width=None, show_name=True, show_unit=None, show_dtype=False, align=None)
Print a formatted string representation of the table.
If no value of
max_lines
is supplied then the height of the screen terminal is used to setmax_lines
. If the terminal height cannot be determined then the default is taken from the configuration itemastropy.conf.max_lines
. If a negative value ofmax_lines
is supplied then there is no line limit applied.The same applies for max_width except the configuration item is
astropy.conf.max_width
.- Parameters:
- max_linesint or None
Maximum number of lines in table output.
- max_widthint or None
Maximum character width of output.
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- show_dtypebool
Include a header row for column dtypes. Default is False.
- alignstr or list or tuple or None
Left/right alignment of columns. Default is right (None) for all columns. Other allowed values are ‘>’, ‘<’, ‘^’, and ‘0=’ for right, left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.
- pprint_all(max_lines=-1, max_width=-1, show_name=True, show_unit=None, show_dtype=False, align=None)
Print a formatted string representation of the entire table.
This method is the same as astropy.table.Table.pprint except that the default
max_lines
andmax_width
are both -1 so that by default the entire table is printed instead of restricting to the size of the screen terminal.- Parameters:
- max_linesint or None
Maximum number of lines in table output.
- max_widthint or None
Maximum character width of output.
- show_namebool
Include a header row for column names. Default is True.
- show_unitbool
Include a header row for unit. Default is to show a row for units only if one or more columns has a defined value for the unit.
- show_dtypebool
Include a header row for column dtypes. Default is False.
- alignstr or list or tuple or None
Left/right alignment of columns. Default is right (None) for all columns. Other allowed values are ‘>’, ‘<’, ‘^’, and ‘0=’ for right, left, centered, and 0-padded, respectively. A list of strings can be provided for alignment of tables with multiple columns.
- pprint_exclude_names
Maintain tuple that controls table column visibility for print output.
This is a descriptor that inherits from MetaAttribute so that the attribute value is stored in the table meta[‘__attributes__’].
This gets used for the
pprint_include_names
andpprint_exclude_names
Table attributes.
- pprint_include_names
Maintain tuple that controls table column visibility for print output.
This is a descriptor that inherits from MetaAttribute so that the attribute value is stored in the table meta[‘__attributes__’].
This gets used for the
pprint_include_names
andpprint_exclude_names
Table attributes.
- property read
Read and parse a data table and return as a Table.
This function provides the Table interface to the astropy unified I/O layer. This allows easily reading a file in many supported data formats using syntax such as:
>>> from astropy.table import Table >>> dat = Table.read('table.dat', format='ascii') >>> events = Table.read('events.fits', format='fits')
Get help on the available readers for
Table
using the``help()`` method:>>> Table.read.help() # Get help reading Table and list supported formats >>> Table.read.help('fits') # Get detailed help on Table FITS reader >>> Table.read.list_formats() # Print list of available formats
See also: https://docs.astropy.org/en/stable/io/unified.html
- Parameters:
- *argstuple, optional
Positional arguments passed through to data reader. If supplied the first argument is typically the input filename.
- formatstr
File format specifier.
- unitslist, dict, optional
List or dict of units to apply to columns
- descriptionslist, dict, optional
List or dict of descriptions to apply to columns
- **kwargsdict, optional
Keyword arguments passed through to data reader.
- Returns:
- out~astropy.table.Table
Table corresponding to file contents
- remove_column(name)
Remove a column from the table.
This can also be done with:
del table[name]
- Parameters:
- namestr
Name of column to remove
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> print(t) a b c --- --- --- 1 0.1 x 2 0.2 y 3 0.3 z
Remove column ‘b’ from the table:
>>> t.remove_column('b') >>> print(t) a c --- --- 1 x 2 y 3 z
To remove several columns at the same time use remove_columns.
- remove_columns(names)
Remove several columns from the table.
- Parameters:
- namesstr or iterable of str
Names of the columns to remove
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> print(t) a b c --- --- --- 1 0.1 x 2 0.2 y 3 0.3 z
Remove columns ‘b’ and ‘c’ from the table:
>>> t.remove_columns(['b', 'c']) >>> print(t) a --- 1 2 3
Specifying only a single column also works. Remove column ‘b’ from the table:
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> t.remove_columns('b') >>> print(t) a c --- --- 1 x 2 y 3 z
This gives the same as using remove_column.
- remove_indices(colname)
Remove all indices involving the given column. If the primary index is removed, the new primary index will be the most recently added remaining index.
- Parameters:
- colnamestr
Name of column
- remove_row(index)
Remove a row from the table.
- Parameters:
- indexint
Index of row to remove
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> print(t) a b c --- --- --- 1 0.1 x 2 0.2 y 3 0.3 z
Remove row 1 from the table:
>>> t.remove_row(1) >>> print(t) a b c --- --- --- 1 0.1 x 3 0.3 z
To remove several rows at the same time use remove_rows.
- remove_rows(row_specifier)
Remove rows from the table.
- Parameters:
- row_specifierslice or int or array of int
Specification for rows to remove
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> print(t) a b c --- --- --- 1 0.1 x 2 0.2 y 3 0.3 z
Remove rows 0 and 2 from the table:
>>> t.remove_rows([0, 2]) >>> print(t) a b c --- --- --- 2 0.2 y
Note that there are no warnings if the slice operator extends outside the data:
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']], ... names=('a', 'b', 'c')) >>> t.remove_rows(slice(10, 20, 1)) >>> print(t) a b c --- --- --- 1 0.1 x 2 0.2 y 3 0.3 z
- rename_column(name, new_name)
Rename a column.
This can also be done directly by setting the
name
attribute of theinfo
property of the column:table[name].info.name = new_name
- Parameters:
- namestr
The current name of the column.
- new_namestr
The new name for the column
Examples
Create a table with three columns ‘a’, ‘b’ and ‘c’:
>>> t = Table([[1,2],[3,4],[5,6]], names=('a','b','c')) >>> print(t) a b c --- --- --- 1 3 5 2 4 6
Renaming column ‘a’ to ‘aa’:
>>> t.rename_column('a' , 'aa') >>> print(t) aa b c --- --- --- 1 3 5 2 4 6
- rename_columns(names, new_names)
Rename multiple columns.
- Parameters:
- nameslist, tuple
A list or tuple of existing column names.
- new_nameslist, tuple
A list or tuple of new column names.
Examples
Create a table with three columns ‘a’, ‘b’, ‘c’:
>>> t = Table([[1,2],[3,4],[5,6]], names=('a','b','c')) >>> print(t) a b c --- --- --- 1 3 5 2 4 6
Renaming columns ‘a’ to ‘aa’ and ‘b’ to ‘bb’:
>>> names = ('a','b') >>> new_names = ('aa','bb') >>> t.rename_columns(names, new_names) >>> print(t) aa bb c --- --- --- 1 3 5 2 4 6
- replace_column(name, col, copy=True)
Replace column
name
with the newcol
object.The behavior of
copy
for Column objects is: - copy=True: new class instance with a copy of data and deep copy of meta - copy=False: new class instance with same data and a key-only copy of metaFor mixin columns: - copy=True: new class instance with copy of data and deep copy of meta - copy=False: original instance (no copy at all)
- Parameters:
- namestr
Name of column to replace
- col~astropy.table.Column or ~numpy.ndarray or sequence
New column object to replace the existing column.
- copybool
Make copy of the input
col
, default=True
See also
Examples
Replace column ‘a’ with a float version of itself:
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3]], names=('a', 'b')) >>> float_a = t['a'].astype(float) >>> t.replace_column('a', float_a)
- reverse()
Reverse the row order of table rows. The table is reversed in place and there are no function arguments.
Examples
Create a table with three columns:
>>> t = Table([['Max', 'Jo', 'John'], ['Miller','Miller','Jackson'], ... [12,15,18]], names=('firstname','name','tel')) >>> print(t) firstname name tel --------- ------- --- Max Miller 12 Jo Miller 15 John Jackson 18
Reversing order:
>>> t.reverse() >>> print(t) firstname name tel --------- ------- --- John Jackson 18 Jo Miller 15 Max Miller 12
- round(decimals=0)
Round numeric columns in-place to the specified number of decimals. Non-numeric columns will be ignored.
- Parameters:
- decimals: int, dict
Number of decimals to round the columns to. If a dict is given, the columns will be rounded to the number specified as the value. If a certain column is not in the dict given, it will remain the same.
Examples
Create three columns with different types:
>>> t = Table([[1, 4, 5], [-25.55, 12.123, 85], ... ['a', 'b', 'c']], names=('a', 'b', 'c')) >>> print(t) a b c --- ------ --- 1 -25.55 a 4 12.123 b 5 85.0 c
Round them all to 0:
>>> t.round(0) >>> print(t) a b c --- ----- --- 1 -26.0 a 4 12.0 b 5 85.0 c
Round column ‘a’ to -1 decimal:
>>> t.round({'a':-1}) >>> print(t) a b c --- ----- --- 0 -26.0 a 0 12.0 b 0 85.0 c
- setdefault(name, default)
Ensure a column named
name
exists.If
name
is already present thendefault
is ignored. Otherwisedefault
can be any data object which is acceptable as a ~astropy.table.Table column object or can be converted. This includes mixin columns and scalar or length=1 objects which get broadcast to match the table length.- Parameters:
- namestr
Name of the column.
- defaultobject
Data object for the new column.
- Returns:
- ~astropy.table.Column, ~astropy.table.MaskedColumn or mixin-column type
The column named
name
if it is present already, or the validateddefault
converted to a column otherwise.
- Raises:
- TypeError
If the table is empty and
default
is a scalar object.
Examples
Start with a simple table:
>>> t0 = Table({"a": ["Ham", "Spam"]}) >>> t0 <Table length=2> a str4 ---- Ham Spam
Trying to add a column that already exists does not modify it:
>>> t0.setdefault("a", ["Breakfast"]) <Column name='a' dtype='str4' length=2> Ham Spam >>> t0 <Table length=2> a str4 ---- Ham Spam
But if the column does not exist it will be created with the default value:
>>> t0.setdefault("approved", False) <Column name='approved' dtype='bool' length=2> False False >>> t0 <Table length=2> a approved str4 bool ---- -------- Ham False Spam False
- show_in_browser(max_lines=5000, jsviewer=False, browser='default', jskwargs={'use_local_files': True}, tableid=None, table_class='display compact', css=None, show_row_index='idx')
Deprecated since version 6.1: We are planning on deprecating show_in_browser in the future. If you are actively using this method, please let us know at https://github.com/astropy/astropy/issues/16067
Render the table in HTML and show it in a web browser.
- Parameters:
- max_linesint
Maximum number of rows to export to the table (set low by default to avoid memory issues, since the browser view requires duplicating the table in memory). A negative value of
max_lines
indicates no row limit.- jsviewerbool
If True, prepends some javascript headers so that the table is rendered as a DataTables data table. This allows in-browser searching & sorting.
- browserstr
Any legal browser name, e.g.
'firefox'
,'chrome'
,'safari'
(for mac, you may need to use'open -a "/Applications/Google Chrome.app" {}'
for Chrome). If'default'
, will use the system default browser.- jskwargsdict
Passed to the astropy.table.JSViewer init. Defaults to
{'use_local_files': True}
which means that the JavaScript libraries will be served from local copies.- tableidstr or None
An html ID tag for the table. Default is
table{id}
, where id is the unique integer id of the table object, id(self).- table_classstr or None
A string with a list of HTML classes used to style the table. Default is “display compact”, and other possible values can be found in https://www.datatables.net/manual/styling/classes
- cssstr
A valid CSS string declaring the formatting for the table. Defaults to
astropy.table.jsviewer.DEFAULT_CSS
.- show_row_indexstr or False
If this does not evaluate to False, a column with the given name will be added to the version of the table that gets displayed. This new column shows the index of the row in the table itself, even when the displayed table is re-sorted by another column. Note that if a column with this name already exists, this option will be ignored. Defaults to “idx”.
- show_in_notebook(tableid=None, css=None, display_length=50, table_class='astropy-default', show_row_index='idx')
Deprecated since version 6.1: show_in_notebook() is deprecated as of 6.1 and to create interactive tables it is recommended to use dedicated tools like: - https://github.com/bloomberg/ipydatagrid - https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html#datatable - https://dash.plotly.com/datatable
Render the table in HTML and show it in the IPython notebook.
- Parameters:
- tableidstr or None
An html ID tag for the table. Default is
table{id}-XXX
, where id is the unique integer id of the table object, id(self), and XXX is a random number to avoid conflicts when printing the same table multiple times.- table_classstr or None
A string with a list of HTML classes used to style the table. The special default string (‘astropy-default’) means that the string will be retrieved from the configuration item
astropy.table.default_notebook_table_class
. Note that these table classes may make use of bootstrap, as this is loaded with the notebook. See this page for the list of classes.- cssstr
A valid CSS string declaring the formatting for the table. Defaults to
astropy.table.jsviewer.DEFAULT_CSS_NB
.- display_lengthint, optional
Number or rows to show. Defaults to 50.
- show_row_indexstr or False
If this does not evaluate to False, a column with the given name will be added to the version of the table that gets displayed. This new column shows the index of the row in the table itself, even when the displayed table is re-sorted by another column. Note that if a column with this name already exists, this option will be ignored. Defaults to “idx”.
Notes
Currently, unlike show_in_browser (with
jsviewer=True
), this method needs to access online javascript code repositories. This is due to modern browsers’ limitations on accessing local files. Hence, if you call this method while offline (and don’t have a cached version of jquery and jquery.dataTables), you will not get the jsviewer features.
- sort(keys=None, *, kind=None, reverse=False)
Sort the table according to one or more keys. This operates on the existing table and does not return a new table.
- Parameters:
- keysstr or list of str
The key(s) to order the table by. If None, use the primary index of the Table.
- kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional
Sorting algorithm used by
numpy.argsort
.- reversebool
Sort in reverse order (default=False)
Examples
Create a table with 3 columns:
>>> t = Table([['Max', 'Jo', 'John'], ['Miller', 'Miller', 'Jackson'], ... [12, 15, 18]], names=('firstname', 'name', 'tel')) >>> print(t) firstname name tel --------- ------- --- Max Miller 12 Jo Miller 15 John Jackson 18
Sorting according to standard sorting rules, first ‘name’ then ‘firstname’:
>>> t.sort(['name', 'firstname']) >>> print(t) firstname name tel --------- ------- --- John Jackson 18 Jo Miller 15 Max Miller 12
Sorting according to standard sorting rules, first ‘firstname’ then ‘tel’, in reverse order:
>>> t.sort(['firstname', 'tel'], reverse=True) >>> print(t) firstname name tel --------- ------- --- Max Miller 12 John Jackson 18 Jo Miller 15
- to_pandas(index=None, use_nullable_int=True)
Return a
pandas.DataFrame
instance.The index of the created DataFrame is controlled by the
index
argument. Forindex=True
or the defaultNone
, an index will be specified for the DataFrame if there is a primary key index on the Table and if it corresponds to a single column. Ifindex=False
then no DataFrame index will be specified. Ifindex
is the name of a column in the table then that will be the DataFrame index.In addition to vanilla columns or masked columns, this supports Table mixin columns like Quantity, Time, or SkyCoord. In many cases these objects have no analog in pandas and will be converted to a “encoded” representation using only Column or MaskedColumn. The exception is Time or TimeDelta columns, which will be converted to the corresponding representation in pandas using
np.datetime64
ornp.timedelta64
. See the example below.- Parameters:
- indexNone, bool, str
Specify DataFrame index mode
- use_nullable_intbool, default=True
Convert integer MaskedColumn to pandas nullable integer type. If
use_nullable_int=False
or the pandas version does not support nullable integer types (version < 0.24), then the column is converted to float with NaN for missing elements and a warning is issued.
- Returns:
- dataframe
pandas.DataFrame
A pandas
pandas.DataFrame
instance
- dataframe
- Raises:
- ImportError
If pandas is not installed
- ValueError
If the Table has multi-dimensional columns
Examples
Here we convert a table with a few mixins to a
pandas.DataFrame
instance.>>> import pandas as pd >>> from astropy.table import QTable >>> import astropy.units as u >>> from astropy.time import Time, TimeDelta >>> from astropy.coordinates import SkyCoord
>>> q = [1, 2] * u.m >>> tm = Time([1998, 2002], format='jyear') >>> sc = SkyCoord([5, 6], [7, 8], unit='deg') >>> dt = TimeDelta([3, 200] * u.s)
>>> t = QTable([q, tm, sc, dt], names=['q', 'tm', 'sc', 'dt'])
>>> df = t.to_pandas(index='tm') >>> with pd.option_context('display.max_columns', 20): ... print(df) q sc.ra sc.dec dt tm 1998-01-01 1.0 5.0 7.0 0 days 00:00:03 2002-01-01 2.0 6.0 8.0 0 days 00:03:20
- update(other, copy=True)
Perform a dictionary-style update and merge metadata.
The argument
other
must be a |Table|, or something that can be used to initialize a table. Columns from (possibly converted)other
are added to this table. In case of matching column names the column from this table is replaced with the one fromother
. Ifother
is a |Table| instance then|=
is available as alternate syntax for in-place update and|
can be used merge data to a new table.- Parameters:
- othertable-like
Data to update this table with.
- copybool
Whether the updated columns should be copies of or references to the originals.
See also
Examples
Update a table with another table:
>>> t1 = Table({'a': ['foo', 'bar'], 'b': [0., 0.]}, meta={'i': 0}) >>> t2 = Table({'b': [1., 2.], 'c': [7., 11.]}, meta={'n': 2}) >>> t1.update(t2) >>> t1 <Table length=2> a b c str3 float64 float64 ---- ------- ------- foo 1.0 7.0 bar 2.0 11.0 >>> t1.meta {'i': 0, 'n': 2}
Update a table with a dictionary:
>>> t = Table({'a': ['foo', 'bar'], 'b': [0., 0.]}) >>> t.update({'b': [1., 2.]}) >>> t <Table length=2> a b str3 float64 ---- ------- foo 1.0 bar 2.0
- values()
- values_equal(other)
Element-wise comparison of table with another table, list, or scalar.
Returns a
Table
with the same columns containing boolean values showing result of comparison.- Parameters:
- othertable-like object or list or scalar
Object to compare with table
Examples
Compare one Table with other:
>>> t1 = Table([[1, 2], [4, 5], [-7, 8]], names=('a', 'b', 'c')) >>> t2 = Table([[1, 2], [-4, 5], [7, 8]], names=('a', 'b', 'c')) >>> t1.values_equal(t2) <Table length=2> a b c bool bool bool ---- ----- ----- True False False True True True
- property write
Write this Table object out in the specified format.
This function provides the Table interface to the astropy unified I/O layer. This allows easily writing a file in many supported data formats using syntax such as:
>>> from astropy.table import Table >>> dat = Table([[1, 2], [3, 4]], names=('a', 'b')) >>> dat.write('table.dat', format='ascii')
Get help on the available writers for
Table
using the``help()`` method:>>> Table.write.help() # Get help writing Table and list supported formats >>> Table.write.help('fits') # Get detailed help on Table FITS writer >>> Table.write.list_formats() # Print list of available formats
The
serialize_method
argument is explained in the section on Table serialization methods.See also: https://docs.astropy.org/en/stable/io/unified.html
- Parameters:
- *argstuple, optional
Positional arguments passed through to data writer. If supplied the first argument is the output filename.
- formatstr
File format specifier.
- serialize_methodstr, dict, optional
Serialization method specifier for columns.
- **kwargsdict, optional
Keyword arguments passed through to data writer.