星系团数据循环读取失败,拼接cluster触发KeyError问题求助
问题根源与解决思路
你遇到的KeyError是因为错误地将多个星系团ID拼接成了一个字符串,而你的DataFrame索引是单个独立的星系团ID(比如A2142、A2744),不存在A2142A2744A2199A119这个索引键,自然找不到对应数据。
要实现逐个读取每个星系团的数据,正确的做法是遍历星系团ID列表,而不是拼接字符串。下面是具体的修改方案:
修正后的代码
from scipy import constants from qconstants import * import os.path import pandas as pd import numpy as np # 注意:你代码中用到了np但未导入,必须添加这行 # 定义星系团ID列表,替代错误的字符串拼接 clusters = ['A2142', 'A2744', 'A2199', 'A119'] ################ List of Cluster################################################################## d1=pd.DataFrame.from_items([ ('A2142' ,['A2142' ,'MH',0.0909 ,418600 ,23 ,129 ,0.57 ,0.810 ,5.82 ,10.0 ,0.5 ,6189.32 ,510 ,2000]), ('A2744' ,['A2744' ,'RH',0.3080 , 28840, 218, 115, 7.7, 0.680, 10.8, 10.0, 0.5, 920.667, 1360, 1100]), ('A2199' ,['A2199' ,'RH',0.0302 , 127000 ,250 , 99.3, 2.0, 0.655, 10.1, 11.7, 0.9, 14655.02, 180, 1000.0]), ('A119' ,['A119' ,'RH',0.0440 ,832000, 243 , 357.9, 5.8, 0.675, 0.15, 7.5, 0.9, 5627.63, 5770, 1100.0])], orient='index',columns=['Label','type','redshift','DL','S_nu','r_c_dum','T_gas_dum','beta','n0','B_dum','eta','rho_s','r_s','r']) ############################# 逐个处理每个星系团数据 ################################################## # 遍历星系团列表,每次处理一个星系团 for cluster in clusters: print(f"正在处理星系团: {cluster}") # 读取当前星系团的属性 redshift = d1.loc[cluster,'redshift'] DL = d1.loc[cluster,'DL'] * kpc * 100.0 # 光度距离,单位cm z = redshift # 替换原来固定的z值,用当前星系团的红移更合理 S_nu = d1.loc[cluster,'S_nu'] # mJy r_c_dum = d1.loc[cluster,'r_c_dum'] # 核心半径 T_gas_dum = d1.loc[cluster,'T_gas_dum'] # 气体温度(keV) beta = d1.loc[cluster,'beta'] # Beta参数 n0 = d1.loc[cluster,'n0'] # 中心电子密度 B_dum = d1.loc[cluster,'B_dum'] # 中心磁场强度 eta = d1.loc[cluster,'eta'] # 磁场分布比例系数 # CMB温度计算 T = T0 * (1.0 + redshift) B0 = B_dum * (10**-6) H_0 = 100.0 * h # 哈勃常数 H_0m = H_0 / (1000.0 * si_pc) Ez = np.sqrt(sigm*(1.0+redshift)**3 + sigl) Hz = H_0m * Ez rho_crit = 3.0 * Hz**2 / (8.0 * constants.pi * si_G) # 临界密度 T_gas = T_gas_dum * 1000.0 * si_e / si_k # 气体温度(开尔文) r_c_dum2 = r_c_dum * 0.5 / h # 转换核心半径单位 r_c = r_c_dum2 * 1000.0 * si_pc * 100.0 # 核心半径(cm) ############################# NFW剖面参数 #################################################### rho_s = d1.loc[cluster,'rho_s'] * rho_crit # 特征密度 r_s = kpc * d1.loc[cluster,'r_s'] # 特征半径(米) r = kpc * d1.loc[cluster,'r'] # 这里可以添加每个星系团的后续处理逻辑,比如保存结果、计算特定指标等 print(f" 红移: {redshift}, 光度距离: {DL:.2e} cm\n")
关键修改说明
- 用列表存储星系团ID:把
cluster变量从拼接字符串改成列表clusters,包含所有需要处理的星系团ID。 - 循环遍历处理:通过
for cluster in clusters逐个取出每个星系团ID,此时cluster是DataFrame中存在的索引键,不会触发KeyError。 - 修复缺失的导入:你代码中使用了
np.sqrt但未导入numpy,必须添加import numpy as np。 - 优化红移取值:把原来固定的
z=0.0302替换为当前星系团的redshift,保证数据对应关系正确。
内容的提问来源于stack exchange,提问作者Raff
相关产品推荐
相关产品推荐

