Astropy
Astropy is a community-developed core Python package for astronomy and astrophysics. It provides a wide range of tools for common astronomical tasks, including units, coordinates, FITS file I/O, and cosmology. The library is actively maintained, with major releases annually, minor releases every six months, and bugfix releases as needed. The current version is 7.2.0.
Warnings
- breaking In Astropy 8.0, deprecated module-level shim files in `astropy.cosmology` were removed. All cosmology classes and functions must now be imported directly from `astropy.cosmology`.
- gotcha Anaconda users upgrading Astropy with `pip` can result in a corrupted installation. It is strongly recommended to use `conda` for updates in Anaconda environments.
- gotcha Astropy `Quantity` objects can sometimes lose their units when used with certain NumPy operations or when broadcasted in specific scenarios. Careful attention is needed to ensure unit preservation.
- gotcha `numpy.prod` cannot be directly applied to `Quantity` instances because the resulting unit depends on the input shape, making correct unit handling ambiguous.
- deprecated The `astropy.test` runner and related API (`astropy.tests.runner.keyword`, `TestRunnerBase`, `TestRunner`) are pending deprecation and will eventually be removed. Downstream packages using `packagename.test` generated with `TestRunner` may also be affected.
- gotcha When defining custom logarithmic units, `u.def_unit` should be avoided as it can lead to unexpected behavior. Logarithmic units should be defined directly.
Install
-
pip install astropy[recommended] -
conda install astropy
Imports
- units
from astropy import units as u
- coordinates
from astropy import coordinates as coord
- SkyCoord
from astropy.coordinates import SkyCoord
- Table
from astropy.table import Table
- fits
from astropy.io import fits
- constants
from astropy import constants as const
- cosmology (classes/functions)
from astropy.cosmology import FlatLambdaCDM, z_at_value
Quickstart
import numpy as np
from astropy import units as u
from astropy import constants as const
from astropy.coordinates import SkyCoord
from astropy.table import Table
# Define a SkyCoord object
pos = SkyCoord(ra=10.68458 * u.deg, dec=41.26917 * u.deg, frame='icrs')
print(f"Sky position: {pos}\n")
# Create a Quantity and perform a calculation
mass = 5.972e24 * u.kg # Earth's mass
radius = 6371 * u.km # Earth's radius
density = mass / (4/3 * np.pi * radius**3)
print(f"Calculated density: {density.to(u.g / u.cm**3):.2f}\n")
# Access a physical constant
c = const.c
print(f"Speed of light: {c.to(u.km/u.s):.0f}\n")
# Create a simple table
data = [
(1, 'NGC 10', 12.5),
(2, 'M 31', 3.4),
(3, 'Abell 2744', 16.0)
]
t = Table(rows=data, names=('id', 'name', 'magnitude'))
print("Example Table:")
print(t)