Skip to main content
Ctrl+K
Astropy
  • About
    • About Astropy
    • Code of Conduct
    • Acknowledging & Citing
    • History
  • Documentation
    • astropy
    • asdf-astropy
    • astropy-healpix
    • astroquery
    • ccdproc
    • photutils
    • regions
    • reproject
    • specreduce
    • specutils
  • Get Help
  • Contribute
  • Affiliated Packages
  • Team
  • GitHub
  • About ▾
    • About Astropy
    • Code of Conduct
    • Acknowledging & Citing
    • History
  • Documentation ▾
    • astropy
    • asdf-astropy
    • astropy-healpix
    • astroquery
    • ccdproc
    • photutils
    • regions
    • reproject
    • specreduce
    • specutils
  • Get Help
  • Contribute
  • Affiliated Packages
  • Team
  • GitHub
Logo image

Astropy v8.0.1

  • Getting Started
    • Installation
    • Importing astropy and Sub-packages
    • Tutorials
  • User Guide
    • Constants (astropy.constants)
      • Constant
      • EMConstant
    • Units and Quantities (astropy.units)
      • Quantity
      • Unit-Aware Type Annotations
      • Standard Units
      • Combining and Defining Units
      • Decomposing and Composing Units
      • Magnitudes and Other Logarithmic Units
      • Structured Units
      • String Representations of Units and Quantities
      • Equivalencies
      • Physical Types
      • Using Prior Versions of Constants
      • Low-Level Unit Conversion
      • Reference/API
        • add_enabled_aliases
        • add_enabled_equivalencies
        • add_enabled_units
        • allclose
        • beam_angular_area
        • brightness_temperature
        • def_physical_type
        • def_unit
        • dimensionless_angles
        • doppler_optical
        • doppler_radio
        • doppler_redshift
        • doppler_relativistic
        • get_current_unit_registry
        • get_physical_type
        • isclose
        • logarithmic
        • magnetic_flux_field
        • mass_energy
        • molar_mass_amu
        • parallax
        • pixel_scale
        • plate_scale
        • quantity_input
        • set_enabled_aliases
        • set_enabled_equivalencies
        • set_enabled_units
        • spectral
        • spectral_density
        • temperature
        • temperature_energy
        • thermodynamic_temperature
        • zero_point_flux
        • CompositeUnit
        • Decibel
        • DecibelUnit
        • Dex
        • DexUnit
        • Equivalency
        • FunctionQuantity
        • FunctionUnitBase
        • IrreducibleUnit
        • LogQuantity
        • LogUnit
        • MagUnit
        • Magnitude
        • NamedUnit
        • PhysicalType
        • PrefixUnit
        • Quantity
        • QuantityInfo
        • QuantityInfoBase
        • SpecificTypeQuantity
        • StructuredUnit
        • Unit
        • UnitBase
        • UnitConversionError
        • UnitParserWarning
        • UnitPrefix
        • UnitScaleError
        • UnitTypeError
        • UnitsError
        • UnitsWarning
        • UnrecognizedUnit
        • enable
        • enable
        • def_physical_type
        • get_physical_type
        • PhysicalType
        • get_format
        • CDS
        • FITS
        • OGIP
        • Base
        • Console
        • Generic
        • Latex
        • LatexInline
        • Unicode
        • VOUnit
    • N-Dimensional Datasets (astropy.nddata)
      • CCDData Class
      • Image Utilities
      • Utility Functions for Handling Bit Masks and Mask Arrays
      • Decorating Functions to Accept NDData Objects
      • NDData
      • Covariance
      • Mixins for Added Functionality
        • Slicing and Indexing NDData
        • NDData Arithmetic
        • I/O Mixin
      • Subclassing
      • Reference/API
        • add_array
        • bitfield_to_boolean_mask
        • block_reduce
        • block_replicate
        • extend_bit_flag_map
        • extract_array
        • fits_ccddata_reader
        • fits_ccddata_writer
        • interpret_bit_flags
        • overlap_slices
        • reshape_as_blocks
        • subpixel_indices
        • support_nddata
        • BitFlagNameMap
        • CCDData
        • Conf
        • Covariance
        • Cutout2D
        • FlagCollection
        • IncompatibleUncertaintiesException
        • InvalidBitFlag
        • InverseVariance
        • MissingDataAssociationException
        • NDArithmeticMixin
        • NDData
        • NDDataArray
        • NDDataBase
        • NDDataRef
        • NDIOMixin
        • NDSlicingMixin
        • NDUncertainty
        • NoOverlapError
        • PartialOverlapError
        • StdDevUncertainty
        • UnknownUncertainty
        • VarianceUncertainty
        • bitfield_to_boolean_mask
        • extend_bit_flag_map
        • interpret_bit_flags
        • BitFlagNameMap
        • InvalidBitFlag
        • add_array
        • extract_array
        • overlap_slices
        • subpixel_indices
        • Cutout2D
        • NoOverlapError
        • PartialOverlapError
    • Data Tables (astropy.table)
      • Constructing a Table
      • Accessing a Table
      • Modifying a Table
      • Table Operations
      • Table Indexing
      • Masking and Missing Values
      • Mixin Columns
      • Interfacing with DataFrames
      • Interfacing with the Pandas Package
      • Astropy Table and DataFrames
      • Table Implementation Details
      • Reference/API
        • dstack
        • hstack
        • join
        • join_distance
        • join_skycoord
        • represent_mixins_as_columns
        • setdiff
        • unique
        • vstack
        • BST
        • Column
        • ColumnGroups
        • ColumnInfo
        • Conf
        • JSViewer
        • MaskedColumn
        • NdarrayMixin
        • PprintIncludeExclude
        • QTable
        • Row
        • SCEngine
        • SerializedColumn
        • SortedArray
        • StringTruncateWarning
        • Table
        • TableAttribute
        • TableColumns
        • TableFormatter
        • TableGroups
        • TableMergeError
        • TableReplaceWarning
        • classic
        • ipydatagrid
    • Time and Dates (astropy.time)
      • Reference/API
        • update_leap_seconds
        • AstropyDatetimeLeapSecondWarning
        • Conf
        • OperandTypeError
        • ScaleValueError
        • Time
        • TimeBase
        • TimeBesselianEpoch
        • TimeBesselianEpochString
        • TimeCxcSec
        • TimeDatetime
        • TimeDatetime64
        • TimeDecimalYear
        • TimeDelta
        • TimeDeltaDatetime
        • TimeDeltaFormat
        • TimeDeltaJD
        • TimeDeltaMissingUnitWarning
        • TimeDeltaNumeric
        • TimeDeltaQuantityString
        • TimeDeltaSec
        • TimeEpochDate
        • TimeEpochDateString
        • TimeFITS
        • TimeFormat
        • TimeFromEpoch
        • TimeGPS
        • TimeGalexSec
        • TimeISO
        • TimeISOT
        • TimeInfo
        • TimeInfoBase
        • TimeJD
        • TimeJulianEpoch
        • TimeJulianEpochString
        • TimeMJD
        • TimeNumeric
        • TimePlotDate
        • TimeString
        • TimeUnique
        • TimeUnix
        • TimeUnixTai
        • TimeYMDHMS
        • TimeYearDayTime
        • TimezoneInfo
    • Time Series (astropy.timeseries)
      • Creating Time Series
      • Reading and Writing Time Series
      • Accessing Data in Time Series
      • Converting between Different Time Representations
      • Manipulation and Analysis of Time Series
      • Masking Values in Time Series
      • Interfacing with the Pandas Package
      • Lomb-Scargle Periodograms
      • Lomb-Scargle Periodograms for Multiband Data
      • Box Least Squares (BLS) Periodogram
      • Reference/API
        • aggregate_downsample
        • autocheck_required_columns
        • BasePeriodogram
        • BaseTimeSeries
        • BinnedTimeSeries
        • BoxLeastSquares
        • BoxLeastSquaresResults
        • LombScargle
        • LombScargleMultiband
        • TimeSeries
        • kepler_fits_reader
    • Astronomical Coordinate Systems (astropy.coordinates)
      • Working with Angles
      • Using the SkyCoord High-Level Class
      • Transforming between Systems
      • Solar System Ephemerides
      • Working with Earth Satellites Using Astropy Coordinates
      • Formatting Coordinate Strings
      • Separations, Offsets, Catalog Matching, and Related Functionality
      • Using and Designing Coordinate Representations
      • Using and Designing Coordinate Frames
      • Working with Velocities in Astropy Coordinates
      • Accounting for Space Motion
      • Using the SpectralCoord Class
      • Using the StokesCoord Class
      • Description of the Galactocentric Coordinate Frame
      • Usage Tips/Suggestions for Methods That Access Remote Resources
      • Common mistakes
      • Important Definitions
      • Fast In-Place Modification of Coordinates
      • Example Gallery
        • Transforming positions and velocities to and from a Galactocentric frame
        • Create a new coordinate frame class for Mars
        • Determining and plotting the altitude/azimuth of a celestial object
        • Create a new coordinate class (for the Sagittarius stream)
        • Convert a radial velocity to the Galactic Standard of Rest (GSR)
      • Reference/API
        • angular_separation
        • cartesian_to_spherical
        • concatenate
        • concatenate_representations
        • custom_stokes_symbol_mapping
        • get_body
        • get_body_barycentric
        • get_body_barycentric_posvel
        • get_constellation
        • get_icrs_coordinates
        • get_sun
        • golden_spiral_grid
        • is_rotation_or_reflection
        • make_transform_graph_docs
        • match_coordinates_3d
        • match_coordinates_sky
        • offset_by
        • position_angle
        • rotation_matrix
        • search_around_3d
        • search_around_sky
        • spherical_to_cartesian
        • uniform_spherical_random_surface
        • uniform_spherical_random_volume
        • AffineTransform
        • AltAz
        • Angle
        • Attribute
        • BarycentricMeanEcliptic
        • BarycentricTrueEcliptic
        • BaseAffineTransform
        • BaseBodycentricRepresentation
        • BaseCoordinateFrame
        • BaseDifferential
        • BaseEclipticFrame
        • BaseGeodeticRepresentation
        • BaseRADecFrame
        • BaseRepresentation
        • BaseRepresentationOrDifferential
        • BaseSphericalCosLatDifferential
        • BaseSphericalDifferential
        • BoundsError
        • CIRS
        • CartesianDifferential
        • CartesianRepresentation
        • CartesianRepresentationAttribute
        • CompositeTransform
        • ConvertError
        • CoordinateAttribute
        • CoordinateFrameInfo
        • CoordinateMatchResult
        • CoordinateSearchResult
        • CoordinateTransform
        • CustomBarycentricEcliptic
        • CylindricalDifferential
        • CylindricalRepresentation
        • DifferentialAttribute
        • Distance
        • DynamicMatrixTransform
        • EarthLocation
        • EarthLocationAttribute
        • FK4
        • FK4NoETerms
        • FK5
        • FunctionTransform
        • FunctionTransformWithFiniteDifference
        • GCRS
        • GRS80GeodeticRepresentation
        • Galactic
        • GalacticLSR
        • Galactocentric
        • GenericFrame
        • GeocentricMeanEcliptic
        • GeocentricTrueEcliptic
        • HADec
        • HCRS
        • HeliocentricEclipticIAU76
        • HeliocentricMeanEcliptic
        • HeliocentricTrueEcliptic
        • ICRS
        • ITRS
        • IllegalHourError
        • IllegalHourWarning
        • IllegalMinuteError
        • IllegalMinuteWarning
        • IllegalSecondError
        • IllegalSecondWarning
        • LSR
        • LSRD
        • LSRK
        • Latitude
        • Longitude
        • NonRotationTransformationError
        • NonRotationTransformationWarning
        • PhysicsSphericalDifferential
        • PhysicsSphericalRepresentation
        • PrecessedGeocentric
        • QuantityAttribute
        • RadialDifferential
        • RadialRepresentation
        • RangeError
        • RepresentationMapping
        • SkyCoord
        • SkyCoordInfo
        • SkyOffsetFrame
        • SpectralCoord
        • SpectralQuantity
        • SphericalCosLatDifferential
        • SphericalDifferential
        • SphericalRepresentation
        • StaticMatrixTransform
        • StokesCoord
        • StokesSymbol
        • Supergalactic
        • TEME
        • TETE
        • TimeAttribute
        • TransformGraph
        • UnitSphericalCosLatDifferential
        • UnitSphericalDifferential
        • UnitSphericalRepresentation
        • UnknownSiteException
        • WGS72GeodeticRepresentation
        • WGS84GeodeticRepresentation
        • galactocentric_frame_defaults
        • solar_system_ephemeris
    • World Coordinate System (astropy.wcs)
      • Shared Python Interface for World Coordinate Systems
      • Legacy Interface
      • Supported Projections
      • Example of Imaging WCS
      • Example of Cube WCS
      • Example of a Planetary WCS
      • Loading From a FITS File
      • Subsetting and Pixel Scales
      • Header-reading relaxation constants
      • astropy.wcs History
      • Validation and Bounds checking
      • Reference/API
        • find_all_wcs
        • get_include
        • validate
        • Auxprm
        • Celprm
        • DistortionLookupTable
        • FITSFixedWarning
        • InconsistentAxisTypesError
        • InvalidCoordinateError
        • InvalidPrjParametersError
        • InvalidSubimageSpecificationError
        • InvalidTabularParametersError
        • InvalidTransformError
        • NoConvergence
        • NoSolutionError
        • NoWcsKeywordsFoundError
        • NonseparableSubimageCoordinateSystemError
        • Prjprm
        • SingularMatrixError
        • Sip
        • Tabprm
        • WCS
        • WCSBase
        • WcsError
        • Wcsprm
        • Wtbarr
        • add_stokes_axis_to_wcs
        • celestial_frame_to_wcs
        • fit_wcs_from_points
        • is_proj_plane_distorted
        • local_partial_pixel_derivatives
        • non_celestial_pixel_scales
        • obsgeo_to_frame
        • pixel_to_pixel
        • pixel_to_skycoord
        • proj_plane_pixel_area
        • proj_plane_pixel_scales
        • skycoord_to_pixel
        • wcs_to_celestial_frame
        • custom_frame_to_wcs_mappings
        • custom_wcs_to_frame_mappings
        • deserialize_class
        • high_level_objects_to_values
        • sanitize_slices
        • validate_physical_types
        • values_to_high_level_objects
        • wcs_info_str
        • BaseHighLevelWCS
        • BaseLowLevelWCS
        • BaseWCSWrapper
        • HighLevelWCSMixin
        • HighLevelWCSWrapper
        • SlicedLowLevelWCS
    • Models and Fitting (astropy.modeling)
      • Models
      • Compound Models
      • Model Parameters
      • Fitting
      • Using Units with Models and Fitting
      • Performance Tips
      • Extending Models
      • Extending Fitters
      • Adding support for units to models
      • JointFitter
      • Parallel Fitting
      • 1D Models
      • 2D Models
      • Physical Models
      • Polynomial Models
      • Powerlaw Models
      • Spline Models
      • Fitting a line
      • Fitting with constraints
      • Fitting Model Sets
      • Reference/API
        • bind_bounding_box
        • bind_compound_bounding_box
        • compose_models_with_units
        • custom_model
        • fix_inputs
        • is_separable
        • separability_matrix
        • CompoundModel
        • Fittable1DModel
        • Fittable2DModel
        • FittableModel
        • InputParameterError
        • Model
        • ModelDefinitionError
        • Parameter
        • ParameterError
        • CompoundBoundingBox
        • ModelBoundingBox
        • Identity
        • Mapping
        • UnitsMapping
        • parallel_fit_dask
        • DogBoxLSQFitter
        • FitInfoArrayContainer
        • Fitter
        • FittingWithOutlierRemoval
        • JointFitter
        • LMLSQFitter
        • LevMarLSQFitter
        • LinearLSQFitter
        • ModelLinearityError
        • ModelsError
        • SLSQPLSQFitter
        • SimplexLSQFitter
        • TRFLSQFitter
        • SLSQP
        • Optimization
        • Simplex
        • leastsquare
        • leastsquare_1d
        • leastsquare_2d
        • leastsquare_3d
        • is_separable
        • separability_matrix
        • AiryDisk2D
        • ArcCosine1D
        • ArcSine1D
        • ArcTangent1D
        • Box1D
        • Box2D
        • Const1D
        • Const2D
        • Cosine1D
        • Disk2D
        • Ellipse2D
        • Exponential1D
        • Gaussian1D
        • Gaussian2D
        • GeneralSersic2D
        • KingProjectedAnalytic1D
        • Linear1D
        • Logarithmic1D
        • Lorentz1D
        • Lorentz2D
        • Moffat1D
        • Moffat2D
        • Multiply
        • Planar2D
        • RedshiftScaleFactor
        • RickerWavelet1D
        • RickerWavelet2D
        • Ring2D
        • Scale
        • Sersic1D
        • Sersic2D
        • Shift
        • Sine1D
        • Tangent1D
        • Trapezoid1D
        • TrapezoidDisk2D
        • Voigt1D
        • NFW
        • BlackBody
        • Drude1D
        • Plummer1D
        • BrokenPowerLaw1D
        • ExponentialCutoffPowerLaw1D
        • LogParabola1D
        • PowerLaw1D
        • Schechter1D
        • SmoothlyBrokenPowerLaw1D
        • SIP
        • Chebyshev1D
        • Chebyshev2D
        • Hermite1D
        • Hermite2D
        • InverseSIP
        • Legendre1D
        • Legendre2D
        • OrthoPolynomialBase
        • Polynomial1D
        • Polynomial2D
        • PolynomialModel
        • AffineTransformation2D
        • Conic
        • Cylindrical
        • HEALPix
        • Pix2SkyProjection
        • Projection
        • PseudoConic
        • PseudoCylindrical
        • QuadCube
        • Sky2PixProjection
        • Zenithal
        • Pix2Sky_ZenithalPerspective
        • Pix2Sky_AZP
        • Pix2Sky_SlantZenithalPerspective
        • Pix2Sky_SZP
        • Pix2Sky_Gnomonic
        • Pix2Sky_TAN
        • Pix2Sky_Stereographic
        • Pix2Sky_STG
        • Pix2Sky_SlantOrthographic
        • Pix2Sky_SIN
        • Pix2Sky_ZenithalEquidistant
        • Pix2Sky_ARC
        • Pix2Sky_ZenithalEqualArea
        • Pix2Sky_ZEA
        • Pix2Sky_Airy
        • Pix2Sky_AIR
        • Pix2Sky_CylindricalPerspective
        • Pix2Sky_CYP
        • Pix2Sky_CylindricalEqualArea
        • Pix2Sky_CEA
        • Pix2Sky_PlateCarree
        • Pix2Sky_CAR
        • Pix2Sky_Mercator
        • Pix2Sky_MER
        • Pix2Sky_SansonFlamsteed
        • Pix2Sky_SFL
        • Pix2Sky_Parabolic
        • Pix2Sky_PAR
        • Pix2Sky_Molleweide
        • Pix2Sky_MOL
        • Pix2Sky_HammerAitoff
        • Pix2Sky_AIT
        • Pix2Sky_ConicPerspective
        • Pix2Sky_COP
        • Pix2Sky_ConicEqualArea
        • Pix2Sky_COE
        • Pix2Sky_ConicEquidistant
        • Pix2Sky_COD
        • Pix2Sky_ConicOrthomorphic
        • Pix2Sky_COO
        • Pix2Sky_BonneEqualArea
        • Pix2Sky_BON
        • Pix2Sky_Polyconic
        • Pix2Sky_PCO
        • Pix2Sky_TangentialSphericalCube
        • Pix2Sky_TSC
        • Pix2Sky_COBEQuadSphericalCube
        • Pix2Sky_CSC
        • Pix2Sky_QuadSphericalCube
        • Pix2Sky_QSC
        • Pix2Sky_HEALPix
        • Pix2Sky_HPX
        • Pix2Sky_HEALPixPolar
        • Pix2Sky_XPH
        • Sky2Pix_ZenithalPerspective
        • Sky2Pix_AZP
        • Sky2Pix_SlantZenithalPerspective
        • Sky2Pix_SZP
        • Sky2Pix_Gnomonic
        • Sky2Pix_TAN
        • Sky2Pix_Stereographic
        • Sky2Pix_STG
        • Sky2Pix_SlantOrthographic
        • Sky2Pix_SIN
        • Sky2Pix_ZenithalEquidistant
        • Sky2Pix_ARC
        • Sky2Pix_ZenithalEqualArea
        • Sky2Pix_ZEA
        • Sky2Pix_Airy
        • Sky2Pix_AIR
        • Sky2Pix_CylindricalPerspective
        • Sky2Pix_CYP
        • Sky2Pix_CylindricalEqualArea
        • Sky2Pix_CEA
        • Sky2Pix_PlateCarree
        • Sky2Pix_CAR
        • Sky2Pix_Mercator
        • Sky2Pix_MER
        • Sky2Pix_SansonFlamsteed
        • Sky2Pix_SFL
        • Sky2Pix_Parabolic
        • Sky2Pix_PAR
        • Sky2Pix_Molleweide
        • Sky2Pix_MOL
        • Sky2Pix_HammerAitoff
        • Sky2Pix_AIT
        • Sky2Pix_ConicPerspective
        • Sky2Pix_COP
        • Sky2Pix_ConicEqualArea
        • Sky2Pix_COE
        • Sky2Pix_ConicEquidistant
        • Sky2Pix_COD
        • Sky2Pix_ConicOrthomorphic
        • Sky2Pix_COO
        • Sky2Pix_BonneEqualArea
        • Sky2Pix_BON
        • Sky2Pix_Polyconic
        • Sky2Pix_PCO
        • Sky2Pix_TangentialSphericalCube
        • Sky2Pix_TSC
        • Sky2Pix_COBEQuadSphericalCube
        • Sky2Pix_CSC
        • Sky2Pix_QuadSphericalCube
        • Sky2Pix_QSC
        • Sky2Pix_HEALPix
        • Sky2Pix_HPX
        • Sky2Pix_HEALPixPolar
        • Sky2Pix_XPH
        • EulerAngleRotation
        • RotateCelestial2Native
        • RotateNative2Celestial
        • Rotation2D
        • RotationSequence3D
        • SphericalRotationSequence
        • Spline1D
        • SplineExactKnotsFitter
        • SplineInterpolateFitter
        • SplineSmoothingFitter
        • SplineSplrepFitter
        • tabular_model
        • Tabular1D
        • Tabular2D
    • Uncertainties and Distributions (astropy.uncertainty)
      • normal
      • poisson
      • uniform
      • Distribution
    • Overview of Astropy File I/O
    • High-level Unified File I/O
      • Image Data
      • Table Data
        • Text (CSV, fixed-width, HTML, and specialized)
        • FITS
        • HDF5
        • Parquet
        • VO Tables
    • FITS File Handling (astropy.io.fits)
      • FITS Headers
      • Image Data
      • Table Data
      • Verification
      • Less Familiar Objects
      • Executable Scripts
      • Miscellaneous Features
      • Obtaining subsets from cloud-hosted FITS files
      • astropy.io.fits FAQ
      • Header Interface Transition Guide
      • astropy.io.fits History
      • Reference/API
        • File Handling and Convenience Functions
        • HDU Lists
        • Header Data Unit
        • Headers
        • Cards
        • Tables
        • Images
        • Differs
        • Verification Options
        • Tiled Compression
    • Text Tables (astropy.io.ascii)
      • Reading Tables
      • Writing Tables
      • ECSV Format
      • Fixed-Width Gallery
      • Fast ASCII I/O
      • Base Class Elements
      • Extension Reader Classes
      • Reference/API
        • convert_numpy
        • get_read_trace
        • get_reader
        • get_writer
        • read
        • set_guess
        • write
        • AASTex
        • AllType
        • BaseData
        • BaseHeader
        • BaseInputter
        • BaseOutputter
        • BaseReader
        • BaseSplitter
        • Basic
        • BasicData
        • BasicHeader
        • Cds
        • Column
        • CommentedHeader
        • Conf
        • ContinuationLinesInputter
        • Csv
        • Daophot
        • DefaultSplitter
        • Ecsv
        • FastBasic
        • FastCommentedHeader
        • FastCsv
        • FastNoHeader
        • FastRdb
        • FastTab
        • FixedWidth
        • FixedWidthData
        • FixedWidthHeader
        • FixedWidthNoHeader
        • FixedWidthSplitter
        • FixedWidthTwoLine
        • FloatType
        • HTML
        • InconsistentTableError
        • IntType
        • Ipac
        • Latex
        • Mesa
        • Mrt
        • NoHeader
        • NoType
        • NumType
        • ParameterError
        • QDP
        • RST
        • Rdb
        • SExtractor
        • StrType
        • Tab
        • TableOutputter
        • Tdat
        • WhitespaceSplitter
    • VOTable Handling (astropy.io.votable)
      • Table element
      • COOSYS element
      • Reading and writing VO model annotations (MIVOT)
      • Reference/API
        • from_table
        • is_votable
        • parse
        • parse_single_table
        • validate
        • writeto
        • Conf
        • CooSys
        • Element
        • Field
        • FieldRef
        • Group
        • Info
        • Link
        • MivotBlock
        • Param
        • ParamRef
        • Resource
        • TableElement
        • TimeSys
        • VOTableFile
        • Values
        • get_converter
        • table_column_to_votable_datatype
        • Converter
        • check_ucd
        • parse_ucd
        • coerce_range_list_param
        • convert_to_writable_filelike
        • make_validation_report
        • check_anyuri
        • check_id
        • check_mime_content_type
        • check_token
        • fix_id
        • validate_schema
        • add_data_origin_info
        • extract_data_origin
        • DataOrigin
        • DatasetOrigin
        • QueryOrigin
      • astropy.io.votable.exceptions
    • ECSV, HDF5, Parquet, PyArrow CSV, YAML (astropy.io.misc)
      • Reference/API
        • fnpickle
        • fnunpickle
        • read_ecsv
        • register_ecsv_table
        • write_ecsv
        • ColumnECSV
        • ECSVEngine
        • ECSVEngineIoAscii
        • ECSVEnginePandas
        • ECSVEnginePyArrow
        • ECSVHeader
        • read_table_hdf5
        • write_table_hdf5
        • convert_pa_table_to_astropy_table
        • read_csv
        • dump
        • load
        • load_all
        • AstropyDumper
        • AstropyLoader
    • Cosmological Calculations (astropy.cosmology)
      • Included Cosmology Realizations
        • available
        • WMAP1
        • WMAP3
        • WMAP5
        • WMAP7
        • WMAP9
        • Planck13
        • Planck15
        • Planck18
      • Units and Equivalencies
        • dimensionless_redshift
        • redshift_distance
        • redshift_hubble
        • redshift_temperature
        • with_H0
        • with_redshift
      • Cosmology I/O & Convert
        • Cosmology I/O Details
        • Built-in Cosmology To/From Formats
        • Custom Cosmology I/O formats
        • CosmologyFromFormat
        • CosmologyRead
        • CosmologyToFormat
        • CosmologyWrite
      • Traits
        • BaryonComponent
        • CriticalDensity
        • CurvatureComponent
        • DarkEnergyComponent
        • DarkMatterComponent
        • HubbleParameter
        • MatterComponent
        • NeutrinoComponent
        • PhotonComponent
        • ScaleFactor
        • TemperatureCMB
        • TotalComponent
      • For Developers
      • Reference/API
        • z_at_value
        • cosmology_equal
        • Cosmology
        • CosmologyError
        • FlatCosmologyMixin
        • FLRW
        • FlatFLRWMixin
        • LambdaCDM
        • FlatLambdaCDM
        • wCDM
        • FlatwCDM
        • w0waCDM
        • Flatw0waCDM
        • w0wzCDM
        • Flatw0wzCDM
        • wpwaCDM
        • FlatwpwaCDM
        • Parameter
        • default_cosmology
    • Convolution and Filtering (astropy.convolution)
      • Using the Convolution Functions
      • Convolution Kernels
      • Convolving with Unnormalized Kernels
      • Reference/API
        • convolve
        • convolve_fft
        • convolve_models
        • convolve_models_fft
        • discretize_model
        • interpolate_replace_nans
        • kernel_arithmetics
        • AiryDisk2DKernel
        • Box1DKernel
        • Box2DKernel
        • CustomKernel
        • Gaussian1DKernel
        • Gaussian2DKernel
        • Kernel
        • Kernel1D
        • Kernel2D
        • KernelArithmeticError
        • KernelError
        • KernelSizeError
        • Model1DKernel
        • Model2DKernel
        • Moffat2DKernel
        • RickerWavelet1DKernel
        • RickerWavelet2DKernel
        • Ring2DKernel
        • Tophat2DKernel
        • Trapezoid1DKernel
        • TrapezoidDisk2DKernel
    • IERS data access (astropy.utils.iers)
    • Data Visualization (astropy.visualization)
      • Plotting Astropy objects in Matplotlib
      • Making plots with world coordinates (WCSAxes)
        • Initializing axes with world coordinates
        • Plotting images and contours
        • Ticks, tick labels, and grid lines
        • Overplotting markers and artists
        • Overlaying coordinate systems
        • Slicing Multidimensional Data
        • Controlling Axes
        • Initializing WCSAxes with custom transforms
        • Using a custom frame
        • add_beam
        • add_scalebar
        • custom_ucd_coord_meta_mapping
        • Conf
        • CoordinateHelper
        • CoordinatesMap
        • Quadrangle
        • SphericalCircle
        • WCSAxes
        • WCSAxesSubplot
        • BaseFrame
        • EllipticalFrame
        • RectangularFrame
        • RectangularFrame1D
        • Spine
      • Image stretching and normalization
      • Choosing Histogram Bins
      • Creating color RGB images
      • Reference/API
        • hist
        • imshow_norm
        • imshow_simple_norm
        • make_lupton_rgb
        • make_rgb
        • quantity_support
        • simple_norm
        • time_support
        • AsinhStretch
        • AsymmetricPercentileInterval
        • BaseInterval
        • BaseStretch
        • BaseTransform
        • CompositeStretch
        • CompositeTransform
        • ContrastBiasStretch
        • HistEqStretch
        • ImageNormalize
        • LinearStretch
        • LogStretch
        • LuptonAsinhStretch
        • LuptonAsinhZscaleStretch
        • ManualInterval
        • MinMaxInterval
        • MplQuantityConverter
        • PercentileInterval
        • PowerDistStretch
        • PowerStretch
        • SimpleNorm
        • SinhStretch
        • SqrtStretch
        • SquaredStretch
        • SymmetricInterval
        • ZScaleInterval
        • imshow_norm
        • imshow_simple_norm
        • simple_norm
        • ImageNormalize
        • SimpleNorm
    • Astrostatistics Tools (astropy.stats)
      • Robust Statistical Estimators
        • sigma_clip
        • sigma_clipped_stats
        • SigmaClip
        • SigmaClippedStats
        • biweight_location
        • biweight_midcorrelation
        • biweight_midcovariance
        • biweight_midvariance
        • biweight_scale
      • Circular Statistics
        • circcorrcoef
        • circmean
        • circmoment
        • circstd
        • circvar
        • rayleightest
        • vonmisesmle
        • vtest
      • Ripley’s K Function Estimators
      • Reference/API
        • binned_binom_proportion
        • binom_conf_interval
        • bootstrap
        • cdf_from_intervals
        • fold_intervals
        • histogram_intervals
        • interval_overlap_length
        • kuiper
        • kuiper_false_positive_probability
        • kuiper_two
        • mad_std
        • median_absolute_deviation
        • poisson_conf_interval
        • signal_to_noise_oir_ccd
        • biweight_location
        • biweight_midcorrelation
        • biweight_midcovariance
        • biweight_midvariance
        • biweight_scale
        • sigma_clip
        • sigma_clipped_stats
        • jackknife_resampling
        • jackknife_stats
        • circcorrcoef
        • circmean
        • circmoment
        • circstd
        • circvar
        • rayleightest
        • vonmisesmle
        • vtest
        • bayesian_blocks
        • calculate_bin_edges
        • freedman_bin_width
        • histogram
        • knuth_bin_width
        • scott_bin_width
        • akaike_info_criterion
        • akaike_info_criterion_lsq
        • bayesian_info_criterion
        • bayesian_info_criterion_lsq
        • SigmaClip
        • SigmaClippedStats
        • Events
        • FitnessFunc
        • PointMeasures
        • RegularEvents
        • RipleysKEstimator
    • Masked Values and Quantities (astropy.utils.masked)
      • combine_masks
      • get_data_and_mask
      • MaskableShapedLikeNDArray
      • Masked
      • MaskedNDArray
      • bincount
      • broadcast_arrays
      • broadcast_to
      • choose
      • copyto
      • count_nonzero
      • full_like
      • insert
      • interp
      • lexsort
      • nanargmax
      • nanargmin
      • nancumprod
      • nancumsum
      • nanmax
      • nanmean
      • nanmedian
      • nanmin
      • nanpercentile
      • nanprod
      • nanquantile
      • nanstd
      • nansum
      • nanvar
      • ones_like
      • piecewise
      • place
      • put
      • select
      • zeros_like
    • SAMP (Simple Application Messaging Protocol) (astropy.samp)
      • Starting and Stopping a SAMP Hub Server
      • Sending and Receiving Tables and Images over SAMP
      • Communication between Integrated Clients Objects
      • Embedding a SAMP Hub in a GUI
      • Reference/API
        • safe_xmlrpc_loads
        • Conf
        • SAMPClient
        • SAMPClientError
        • SAMPHubError
        • SAMPHubProxy
        • SAMPHubServer
        • SAMPIntegratedClient
        • SAMPMsgReplierWrapper
        • SAMPProxyError
        • SAMPWarning
        • SAMPXXEServerProxy
        • WebProfileDialog
    • Configuration System (astropy.config)
      • Astropy’s Default Configuration File
      • Reference/API
        • create_config_file
        • generate_config
        • get_cache_dir
        • get_cache_dir_path
        • get_config
        • get_config_dir
        • get_config_dir_path
        • reload_config
        • temporary_cache_dir_path
        • temporary_config_dir_path
        • ConfigItem
        • ConfigNamespace
        • InvalidConfigurationItemWarning
        • set_temp_cache
        • set_temp_config
    • I/O Registry (astropy.io.registry)
      • Reference/API
        • delay_doc_updates
        • get_formats
        • get_reader
        • get_writer
        • identify_format
        • read
        • register_identifier
        • register_reader
        • register_writer
        • unregister_identifier
        • unregister_reader
        • unregister_writer
        • write
        • UnifiedIORegistry
        • UnifiedInputRegistry
        • UnifiedOutputRegistry
        • UnifiedReadWrite
        • UnifiedReadWriteMethod
        • IORegistryError
    • I/O Typing (astropy.io.typing)
      • ReadableFileLike
      • WriteableFileLike
    • Logging system
      • AstropyLogger
      • Conf
      • LoggingError
    • Python warnings system
    • Astropy Core Package Utilities (astropy.utils)
      • Downloadable Data Management (astropy.utils.data)
      • Reference/API
        • make_function_with_signature
        • HomogeneousList
        • color_print
        • human_file_size
        • human_time
        • isatty
        • print_code_line
        • terminal_size
        • ProgressBar
        • ProgressBarOrSpinner
        • Spinner
        • data_info_factory
        • dtype_info_name
        • BaseColumnInfo
        • DataInfo
        • MixinInfo
        • ParentDtypeInfo
        • deprecated
        • deprecated_attribute
        • deprecated_renamed_argument
        • format_doc
        • classproperty
        • lazyproperty
        • sharedmethod
        • diff_values
        • report_diff_values
        • where_not_allclose
        • AstropyBackwardsIncompatibleChangeWarning
        • AstropyDeprecationWarning
        • AstropyPendingDeprecationWarning
        • AstropyUserWarning
        • AstropyWarning
        • DuplicateRepresentationWarning
        • Conf
        • IERS
        • IERSDegradedAccuracyWarning
        • IERSRangeError
        • IERSStaleWarning
        • IERSWarning
        • IERS_A
        • IERS_Auto
        • IERS_B
        • LeapSeconds
        • earth_orientation_table
        • find_current_module
        • isinstancemethod
        • minversion
        • resolve_name
        • enable_merge_strategies
        • merge
        • common_dtype
        • MetaAttribute
        • MetaData
        • MergeNpConcatenate
        • MergePlus
        • MergeStrategy
        • MergeConflictError
        • MergeConflictWarning
        • dtype_bytes_or_chars
        • find_api_page
        • format_exception
        • indent
        • isiterable
        • online_help
        • silence
        • JsonCustomEncoder
        • NumpyRNGContext
        • lex
        • yacc
        • ThreadSafeParser
        • ScienceState
        • check_broadcast
        • simplify_basic_index
        • unbroadcast
        • IncompatibleShapeError
        • NDArrayShapeMethods
        • ShapedLikeNDArray
        • system_info
        • cache_contents
        • cache_total_size
        • check_download_cache
        • check_free_space_in_dir
        • clear_download_cache
        • compute_hash
        • download_file
        • download_files_in_parallel
        • export_download_cache
        • get_cached_urls
        • get_file_contents
        • get_free_space_in_dir
        • get_pkg_data_contents
        • get_pkg_data_filename
        • get_pkg_data_filenames
        • get_pkg_data_fileobj
        • get_pkg_data_fileobjs
        • get_pkg_data_path
        • get_readable_fileobj
        • import_download_cache
        • import_file_to_cache
        • is_url
        • is_url_in_cache
        • CacheDamaged
        • CacheMissingWarning
        • Conf
        • check_anyuri
        • check_id
        • check_mime_content_type
        • check_token
        • fix_id
        • get_xml_encoding
        • get_xml_iterator
        • xml_readlines
        • unescape_all
        • validate_schema
        • XMLWriter
    • Environment variables
    • Astropy Glossary
  • Contributing
  • Project Details
    • What’s New
      • What’s New in Astropy 8.0?
    • Full Changelog
    • LTS Backport Policy
    • Known Issues
    • Authors and Credits
    • Impact and Health
    • Licenses
  • User Guide
  • Text Tables (astropy.io.ascii)
  • Fixed-Width Gallery

Fixed-Width Gallery#

Fixed-width tables are those where each column has the same width for every row in the table. This is commonly used to make tables easy to read for humans or Fortran codes. It also reduces issues with quoting and special characters, for example:

Col1   Col2    Col3 Col4
---- --------- ---- ----
 1.2   "hello"    1    a
 2.4 's worlds    2    2

There are a number of common variations in the formatting of fixed-width tables which astropy.io.ascii can read and write. The most significant difference is whether there is no header line (FixedWidthNoHeader), one header line (FixedWidth), or two header lines (FixedWidthTwoLine). Next, there are variations in the delimiter character, like whether the delimiter appears on either end (“bookends”), or if there is padding around the delimiter.

Details are available in the class API documentation, but the easiest way to understand all of the options and their interactions is by example.

Reading#

Fixed Width#

Nice, typical, fixed-format table:

>>> from astropy.io import ascii
>>> table = """
... # comment (with blank line above)
... |  Col1  |  Col2   |
... |  1.2   | "hello" |
... |  2.4   |'s worlds|
... """
>>> ascii.read(table, format='fixed_width')
<Table length=2>
  Col1     Col2
float64    str9
------- ---------
    1.2   "hello"
    2.4 's worlds

Typical fixed-format table with col names provided:

>>> table = """
... # comment (with blank line above)
... |  Col1  |  Col2   |
... |  1.2   | "hello" |
... |  2.4   |'s worlds|
... """
>>> ascii.read(table, format='fixed_width', names=['name1', 'name2'])
<Table length=2>
 name1    name2
float64    str9
------- ---------
    1.2   "hello"
    2.4 's worlds

Weird input table with data values chopped by col extent:

>>> table = """
...   Col1  |  Col2 |
...   1.2       "hello"
...   2.4   sdf's worlds
... """
>>> ascii.read(table, format='fixed_width')
<Table length=2>
  Col1    Col2
float64   str7
------- -------
    1.2    "hel
    2.4 df's wo

Table with double delimiters:

>>> table = """
... || Name ||   Phone ||         TCP||
... |  John  | 555-1234 |192.168.1.10X|
... |  Mary  | 555-2134 |192.168.1.12X|
... |   Bob  | 555-4527 | 192.168.1.9X|
... """
>>> ascii.read(table, format='fixed_width')
<Table length=3>
Name  Phone       TCP
str4   str8      str12
---- -------- ------------
John 555-1234 192.168.1.10
Mary 555-2134 192.168.1.12
 Bob 555-4527  192.168.1.9

Table with space delimiter:

>>> table = """
...  Name  --Phone-    ----TCP-----
...  John  555-1234    192.168.1.10
...  Mary  555-2134    192.168.1.12
...   Bob  555-4527     192.168.1.9
... """
>>> ascii.read(table, format='fixed_width', delimiter=' ')
<Table length=3>
Name --Phone- ----TCP-----
str4   str8      str12
---- -------- ------------
John 555-1234 192.168.1.10
Mary 555-2134 192.168.1.12
 Bob 555-4527  192.168.1.9

Table with no header row and auto-column naming:

Use header_start and data_start keywords to indicate no header line.

>>> table = """
... |  John  | 555-1234 |192.168.1.10|
... |  Mary  | 555-2134 |192.168.1.12|
... |   Bob  | 555-4527 | 192.168.1.9|
... """
>>> ascii.read(table, format='fixed_width',
...            header_start=None, data_start=0)
<Table length=3>
col1   col2       col3
str4   str8      str12
---- -------- ------------
John 555-1234 192.168.1.10
Mary 555-2134 192.168.1.12
 Bob 555-4527  192.168.1.9

Table with no header row and with col names provided:

Second and third rows also have hanging spaces after final “|”. Use header_start and data_start keywords to indicate no header line.

>>> table = ["|  John  | 555-1234 |192.168.1.10|",
...          "|  Mary  | 555-2134 |192.168.1.12|  ",
...          "|   Bob  | 555-4527 | 192.168.1.9|  "]
>>> ascii.read(table, format='fixed_width',
...            header_start=None, data_start=0,
...            names=('Name', 'Phone', 'TCP'))
<Table length=3>
Name  Phone       TCP
str4   str8      str12
---- -------- ------------
John 555-1234 192.168.1.10
Mary 555-2134 192.168.1.12
 Bob 555-4527  192.168.1.9

Fixed Width No Header#

Table with no header row and auto-column naming. Use the ``fixed_width_no_header`` format for convenience:

>>> table = """
... |  John  | 555-1234 |192.168.1.10|
... |  Mary  | 555-2134 |192.168.1.12|
... |   Bob  | 555-4527 | 192.168.1.9|
... """
>>> ascii.read(table, format='fixed_width_no_header')
<Table length=3>
col1   col2       col3
str4   str8      str12
---- -------- ------------
John 555-1234 192.168.1.10
Mary 555-2134 192.168.1.12
 Bob 555-4527  192.168.1.9

Table with no delimiter with column start and end values specified:

This uses the col_starts and col_ends keywords. Note that the col_ends values are inclusive so a position range of zero to five will select the first six characters.

>>> table = """
... #    5   9     17  18      28    <== Column start / end indexes
... #    |   |       ||         |    <== Column separation positions
...   John   555- 1234 192.168.1.10
...   Mary   555- 2134 192.168.1.12
...    Bob   555- 4527  192.168.1.9
... """
>>> ascii.read(table, format='fixed_width_no_header',
...                 names=('Name', 'Phone', 'TCP'),
...                 col_starts=(0, 9, 18),
...                 col_ends=(5, 17, 28),
...                 )
<Table length=3>
Name   Phone      TCP
str4    str9     str10
---- --------- ----------
John 555- 1234 192.168.1.
Mary 555- 2134 192.168.1.
 Bob 555- 4527  192.168.1

Table with no delimiter with only column start or end values specified:

If only the col_starts keyword is given, it is assumed that each column ends where the next column starts, and the final column ends at the same position as the longest line of data.

Conversely, if only the col_ends keyword is given, it is assumed that the first column starts at position zero and that each successive column starts immediately after the previous one.

The two examples below read the same table and produce the same result.

>>> table = """
... #1       9        19                <== Column start indexes
... #|       |         |                <== Column start positions
... #<------><--------><------------->  <== Inferred column positions
...   John   555- 1234 192.168.1.10
...   Mary   555- 2134 192.168.1.123
...    Bob   555- 4527  192.168.1.9
...    Bill  555-9875  192.255.255.255
... """
>>> ascii.read(table,
...                 format='fixed_width_no_header',
...                 names=('Name', 'Phone', 'TCP'),
...                 col_starts=(1, 9, 19),
...                 )
<Table length=4>
Name   Phone         TCP
str4    str9        str15
---- --------- ---------------
John 555- 1234    192.168.1.10
Mary 555- 2134   192.168.1.123
 Bob 555- 4527     192.168.1.9
Bill  555-9875 192.255.255.255

>>> ascii.read(table,
...                 format='fixed_width_no_header',
...                 names=('Name', 'Phone', 'TCP'),
...                 col_ends=(8, 18, 32),
...                 )
<Table length=4>
Name   Phone        TCP
str4    str9       str14
---- --------- --------------
John 555- 1234   192.168.1.10
Mary 555- 2134  192.168.1.123
 Bob 555- 4527    192.168.1.9
Bill  555-9875 192.255.255.25

Fixed Width Two Line#

Typical fixed-format table with two header lines with some cruft:

>>> table = """
...   Col1    Col2
...   ----  ---------
...    1.2xx"hello"
...   2.4   's worlds
... """
>>> ascii.read(table, format='fixed_width_two_line')
<Table length=2>
  Col1     Col2
float64    str9
------- ---------
    1.2   "hello"
    2.4 's worlds

reStructuredText table:

>>> table = """
... ======= ===========
...   Col1    Col2
... ======= ===========
...   1.2   "hello"
...   2.4   's worlds
... ======= ===========
... """
>>> ascii.read(table, format='fixed_width_two_line',
...                 header_start=1, position_line=2, data_end=-1)
<Table length=2>
  Col1     Col2
float64    str9
------- ---------
    1.2   "hello"
    2.4 's worlds

Text table designed for humans and test having position line before the header line:

>>> table = """
... +------+----------+
... | Col1 |   Col2   |
... +------|----------+
... |  1.2 | "hello"  |
... |  2.4 | 's worlds|
... +------+----------+
... """
>>> ascii.read(table, format='fixed_width_two_line', delimiter='+',
...                 header_start=1, position_line=0, data_start=3, data_end=-1)
<Table length=2>
  Col1     Col2
float64    str9
------- ---------
    1.2   "hello"
    2.4 's worlds

Writing#

Fixed Width#

Define input values ``dat`` for all write examples:

>>> table = """
... | Col1 |  Col2     |  Col3 | Col4 |
... | 1.2  | "hello"   |  1    | a    |
... | 2.4  | 's worlds |  2    | 2    |
... """
>>> dat = ascii.read(table, format='fixed_width')

Write a table as a normal fixed-width table:

>>> ascii.write(dat, format='fixed_width')
| Col1 |      Col2 | Col3 | Col4 |
|  1.2 |   "hello" |    1 |    a |
|  2.4 | 's worlds |    2 |    2 |

Write a table as a fixed-width table with no padding:

>>> ascii.write(dat, format='fixed_width', delimiter_pad=None)
|Col1|     Col2|Col3|Col4|
| 1.2|  "hello"|   1|   a|
| 2.4|'s worlds|   2|   2|

Write a table as a fixed-width table with no bookend:

>>> ascii.write(dat, format='fixed_width', bookend=False)
Col1 |      Col2 | Col3 | Col4
 1.2 |   "hello" |    1 |    a
 2.4 | 's worlds |    2 |    2

Write a table as a fixed-width table with no delimiter:

>>> ascii.write(dat, format='fixed_width', bookend=False, delimiter=None)
Col1       Col2  Col3  Col4
 1.2    "hello"     1     a
 2.4  's worlds     2     2

Write a table as a fixed-width table with no delimiter and formatting:

>>> ascii.write(dat, format='fixed_width',
...                  formats={'Col1': '%-8.3f', 'Col2': '%-15s'})
|     Col1 |            Col2 | Col3 | Col4 |
| 1.200    | "hello"         |    1 |    a |
| 2.400    | 's worlds       |    2 |    2 |

Fixed Width No Header#

Write a table as a normal fixed-width table:

>>> ascii.write(dat, format='fixed_width_no_header')
| 1.2 |   "hello" | 1 | a |
| 2.4 | 's worlds | 2 | 2 |

Write a table as a fixed-width table with no padding:

>>> ascii.write(dat, format='fixed_width_no_header', delimiter_pad=None)
|1.2|  "hello"|1|a|
|2.4|'s worlds|2|2|

Write a table as a fixed-width table with no bookend:

>>> ascii.write(dat, format='fixed_width_no_header', bookend=False)
1.2 |   "hello" | 1 | a
2.4 | 's worlds | 2 | 2

Write a table as a fixed-width table with no delimiter:

>>> ascii.write(dat, format='fixed_width_no_header', bookend=False,
...                  delimiter=None)
1.2    "hello"  1  a
2.4  's worlds  2  2

Fixed Width Two Line#

Write a table as a normal fixed-width table:

>>> ascii.write(dat, format='fixed_width_two_line')
Col1      Col2 Col3 Col4
---- --------- ---- ----
 1.2   "hello"    1    a
 2.4 's worlds    2    2

Write a table as a fixed width table with space padding and ‘=’ position_char:

>>> ascii.write(dat, format='fixed_width_two_line',
...                  delimiter_pad=' ', position_char='=')
Col1        Col2   Col3   Col4
====   =========   ====   ====
 1.2     "hello"      1      a
 2.4   's worlds      2      2

Write a table as a fixed-width table with no bookend:

>>> ascii.write(dat, format='fixed_width_two_line', bookend=True, delimiter='|')
|Col1|     Col2|Col3|Col4|
|----|---------|----|----|
| 1.2|  "hello"|   1|   a|
| 2.4|'s worlds|   2|   2|

Custom Header Rows#

The fixed_width, fixed_width_two_line, and rst formats normally include a single row with the column names in the header. However, for these formats you can customize the column attributes which appear as header rows. The available column attributes are name, dtype, format, description and unit. This is done by listing the desired the header rows using the header_rows keyword argument.

::
>>> from astropy.table.table_helpers import simple_table
>>> dat = simple_table(size=3, cols=4)
>>> dat["a"].info.unit = "m"
>>> dat["d"].info.unit = "m/s"
>>> dat["b"].info.format = ".2f"
>>> dat["c"].info.description = "C column"
>>> ascii.write(
...    dat,
...    format="fixed_width",
...    header_rows=["name", "unit", "format", "description"],
... )
|     a |       b |        c |     d |
|     m |         |          | m / s |
|       |     .2f |          |       |
|       |         | C column |       |
|     1 |    1.00 |        c |     4 |
|     2 |    2.00 |        d |     5 |
|     3 |    3.00 |        e |     6 |

In this example the 1st row is the name, the 2nd row is the unit, and so forth. You must supply the name value in the header_rows list in order to get an output with the column name included.

A table with non-standard header rows can be read back in the same way, using the same list of header_rows:

>>> txt = """\
... | int32 | float32 |      <U4 | uint8 |
... |     a |       b |        c |     d |
... |     m |         |          | m / s |
... |       |     .2f |          |       |
... |       |         | C column |       |
... |     1 |    1.00 |        c |     4 |
... |     2 |    2.00 |        d |     5 |
... |     3 |    3.00 |        e |     6 |
... """
>>> dat = ascii.read(
...     txt,
...     format="fixed_width",
...     header_rows=["dtype", "name", "unit", "format", "description"],
... )
>>> dat.info
<Table length=3>
name  dtype   unit format description
---- ------- ----- ------ -----------
a   int32     m
b float32          .2f
c    str4                 C column
d   uint8 m / s

The same idea can be used with the fixed_width_two_line format:

>>> txt = """\
...     a       b        c     d
... int64 float64      <U1 int64
...     m                  m / s
... ----- ------- -------- -----
...     1    1.00        c     4
...     2    2.00        d     5
...     3    3.00        e     6
... """
>>> dat = ascii.read(
...     txt,
...     format="fixed_width_two_line",
...     header_rows=["name", "dtype", "unit"],
... )
>>> dat
<Table length=3>
  a      b     c     d
  m                m / s
int64 float64 str1 int64
----- ------- ---- -----
    1     1.0    c     4
    2     2.0    d     5
    3     3.0    e     6

Note that the two_line in the fixed_width_two_line format name refers to the default situation where the header consists two lines, a row of column names and a row of separator lines. This is a bit of a misnomer when using header_rows.

previous

ECSV Format

next

Fast ASCII I/O

On this page
  • Reading
    • Fixed Width
    • Fixed Width No Header
    • Fixed Width Two Line
  • Writing
    • Fixed Width
    • Fixed Width No Header
    • Fixed Width Two Line
  • Custom Header Rows
Edit

© Copyright 2011–2026, The Astropy Developers.

Code of Conduct

Updated on 30 Sep 2026 , built with Sphinx 8.2.3