[ SKILL_DOCUMENTATION ]
# 表格操作 (astropy.table)
`astropy.table` 模块提供了用于处理表格数据的灵活工具,支持单位、掩码值和多种文件格式。
## 创建表格
### 基本表格创建
python
from astropy.table import Table, QTable
import astropy.units as u
import numpy as np
# 从列数组创建
a = [1, 4, 5]
b = [2.0, 5.0, 8.2]
c = ['x', 'y', 'z']
t = Table([a, b, c], names=('id', 'flux', 'name'))
# 使用单位 (使用 QTable)
flux = [1.2, 2.3, 3.4] * u.Jy
wavelength = [500, 600, 700] * u.nm
t = QTable([flux, wavelength], names=('flux', 'wavelength'))
### 从行列表创建
python
# 元组列表
rows = [(1, 10.5, 'A'), (2, 11.2, 'B'), (3, 12.3, 'C')]
t = Table(rows=rows, names=('id', 'value', 'name'))
# 字典列表
rows = [{'id': 1, 'value': 10.5}, {'id': 2, 'value': 11.2}]
t = Table(rows)
### 从 NumPy 数组创建
python
# 结构化数组
arr = np.array([(1, 2.0, 'x'), (4, 5.0, 'y')],
dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'U10')])
t = Table(arr)
# 带有列名的二维数组
data = np.random.random((100, 3))
t = Table(data, names=['col1', 'col2', 'col3'])
### 从 Pandas DataFrame 创建
python
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
t = Table.from_pandas(df)
## 访问表格数据
### 基本访问
python
# 列访问
ra_col = t['ra'] # 返回 Column 对象
dec_col = t['dec']
# 行访问
first_row = t[0] # 返回 Row 对象
row_slice = t[10:20] # 返回新表格
# 单元格访问
value = t['ra'][5] # 'ra' 列中的第 6 个值
value = t[5]['ra'] # 同上
# 多列访问
subset = t['ra', 'dec', 'mag']
### 表格属性
python
len(t) # 行数
t.colnames # 列名列表
t.dtype # 列数据类型
t.info # 详细信息
t.meta # 元数据字典
### 迭代
python
# 遍历行
for row in t:
print(row['ra'], row['dec'])
# 遍历列
for colname in t.colnames:
print(t[colname])
## 修改表格
### 添加列
python
# 添加新列
t['new_col'] = [1, 2, 3, 4, 5]
t['calc'] = t['a'] + t['b'] # 计算列
# 添加带单位的列
t['velocity'] = [10, 20, 30] * u.km / u.s
# 添加空列
from astropy.table import Column
t['empty'] = Column(length=len(t), dtype=float)
# 在特定位置插入
t.add_column([7, "