You need to enable JavaScript to run this app. Python读取fits文件参数后如何将多个列表作为列生成打印表格
优惠活动
大模型
产品
解决方案
定价
更多

Python读取fits文件参数后如何将多个列表作为列生成打印表格

问题描述

我在Ubuntu 20.10系统的IDLE编辑器中使用Python 3.8.10版本。
我需要从多个.fits格式文件中读取部分参数,已经编写了对应的readfits函数,能够打开文件并将所需参数值添加到对应的列表中。现在需要编写函数对当前目录下的指定文件调用readfits方法,随后将所有参数打印为表格形式。
目前遇到的问题是现有每个列表对应表格的一列,不知道如何实现表格生成。由于总共有104个.fits文件,手动处理工作量极大,需要通过批量方式实现。

以下是目前编写的代码:

#import needed packages
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
import os
from tabulate import tabulate

#make empty lists where rquantities will be added
rv = []
date = []
rv_errors = []
airmass = []
BIS = []
normal_dates = []
names = []
instrument = []


#create function which reads .fits files and adds values to global lists
def readfits(filename):

    #open files and give names to data and header
    with fits.open(filename) as hdu:
        data = hdu[0].data
        head = hdu[0].header

    #Useful quantities
    
    #Contrast of CCF in %
    contrast = head['HIERARCH TNG DRS CCF CONTRAST']

    #FWHM of CCF in km/s
    fwhm_ccf = head['HIERARCH TNG DRS CCF FWHM']

    #Number of lines used
    nr_lines = head['HIERARCH TNG DRS CCF LINES']

    #Mask type
    mask = head['HIERARCH TNG DRS CCF MASK']

    #Right ascension and declination in radians
    ra = head['RA']
    dec = head['DEC']

    #Air mass
    air_mass = head['AIRMASS']

    #Mean Julian Date of observation
    jd = head['MJD-OBS']

    #Mean BJD subtracted for plotting reasons
    bjd = head['HIERARCH TNG DRS BJD'] - 2450000

    #Exposure time in s
    exp_time = head['EXPTIME']

    #Estimated RV uncertainty in m/s
    err_rv = head['HIERARCH TNG DRS DVRMS']

    #Noise at order 46 where the stellar peak is
    #sn46 = head['HIERARCH TNG DRS SPE EXT SN46']

    #Half-window of the CCF
    half_wind = head['HIERARCH IA2 YABI WIDTHCCF']

    #Step of the CCF
    ccf_step = head['HIERARCH IA2 YABI STEPCCF']

    #Apparent magnitude
    mag = head['HIERARCH TNG TEL TARG MAG']

    #Th-lamp drift
    th_drift = head['HIERARCH TNG DRS DRIFT SPE RV']

    #RV of the system (YABI input)
    #rv_sys = head['HIERARCH TNG TEL TARG RADVEL']

    #BIS
    bis = head['HIERARCH TNG DRS BIS SPAN']

    #CCF noise from km/s to m/s
    ccf_noise = head['HIERARCH TNG DRS CCF NOISE']*1000

    #Measured RV for this target in this night in km/s
    rv_mis = head['HIERARCH TNG DRS CCF RVC']

    #RV in m/s
    rv_true = rv_mis*1000

    #readable date
    dates = head['DATE-OBS']

    #instrument used
    strum = head['INSTRUME']

    #name of target
    name = head['HIERARCH TNG OBS TARG NAME']

    #add quantities to the initial lists
    global rv
    rv.append(rv_true)
    global date
    date.append(bjd)
    global rv_errors
    rv_errors.append(ccf_noise)
    global airmass
    airmass.append(air_mass)
    global BIS
    BIS.append(bis)
    global normal_dates
    normal_dates.append(dates)
    global instrument
    instrument.append(strum)
    global names
    names.append(name)


#writes values from fits files to txt table
def writetable():

    #list with all files in directory
    list_all = os.listdir()
    list_data = []

    #take only files with 'bis' in the name
    for i in range(0, len(list_all)):
        if 'bis' in list_all[i]:
            list_data.append(list_all[i])

    #sort elements in alphabetical order
    list_data.sort()

    #apply readfits to all 'bis' files
    n = len(list_data)
    for i in range(0,n):
        readfits(list_data[i])
    
    global names
    global normal_dates
    global instrument
    global rv
    global rv_errors
    global date
    global BIS
    global airmass
    
    #headers for table
    headers = ['Target', 'Date of observation', 'Instrument', 'RV',
               'RV error', 'BJD', 'BIS', 'Air mass']

    
    param_table = tabulate([], headers = headers)
    
    print(param_table)
解决方案

你当前代码的问题是调用tabulate时传入了空列表,自然无法生成带数据的表格。你已经将所有文件的参数按文件顺序存入了长度相同的列表,同一索引位置的元素对应同一个fits文件的不同参数,只需要将这些列按表头顺序拼接为行数据传入tabulate即可。
只需要修改writetable函数的末尾部分即可:

# 表头可保留英文,也可自行替换为中文
    headers = ['目标名称', '观测日期', '观测设备', '视向速度(m/s)',
               '视向速度误差(m/s)', '约化儒略日', 'BIS跨度', '大气质量']
    # 按表头顺序拼接所有列生成行数据
    table_rows = list(zip(names, normal_dates, instrument, rv, rv_errors, date, BIS, airmass))
    # 生成表格,可通过tablefmt调整输出格式,可选值包括simple、grid、markdown等
    param_table = tabulate(table_rows, headers=headers, tablefmt='simple')
    # 打印表格
    print(param_table)
    # 若需要保存为本地文件可添加以下代码
    with open('fits参数统计.txt', 'w', encoding='utf-8') as f:
        f.write(param_table)

内容的提问来源于stack exchange,提问作者Alessandro Ruggieri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 20:48:00