Skip to main content
 首页 » 编程设计

Python astropy : table and columns objects

2024年10月24日7cmt

我正在使用 astropy.table 模块中的 Tables 对象。

下面的一段代码显示了我正在处理的数据类型:

In [44]: table              
Out[44]:  
<Table length=9> 
defocus  source   Chi2  xcentroid ycentroid  FWHMx   FWHMy    Peak  
float32 float32 float32  float32   float32  float32 float32 float32 
------- ------- ------- --------- --------- ------- ------- ------- 
   -0.3     0.0 346.648    2056.5     55.82 11.8635 11.8635 182.277 
   -0.3     4.0 148.302   2056.49   1911.02 6.66554 6.66554 299.074 
   -0.3     8.0 347.208   2056.51   3922.99 6.83129 6.83129 326.476 
  -0.26     0.0 318.489    2056.5   55.8803  10.206  10.206 195.055 
  -0.26     4.0 152.501   2056.51   1911.02  6.9012  6.9012 244.817 
  -0.26     8.0 285.845   2056.49   3922.99  7.7939  7.7939 236.194 
  -0.22     0.0 264.113    2056.5   55.9053 8.79704 8.79704 187.376 
  -0.22     4.0 163.228    2056.5   1911.02 2.43716 2.43716 402.182 
  -0.22     8.0 230.017    2056.5   3922.99 6.70312 6.70312 235.376 
 
In [45]: type(table)        
Out[45]: astropy.table.table.Table 
 
In [46]: cols=table.columns 
 
In [47]: type(cols) 
Out[47]: astropy.table.table.TableColumns 
 
In [48]: type(cols[0]) 
Out[48]: astropy.table.column.Column  
 
In [50]: mylist_1 = [x for x in cols] 
 
In [51]: mylist_2 = [cols[k] for k in range(len(cols))] 
 
In [52]: type(mylist_1[0]) 
Out[52]: str 
 
In [53]: type(mylist_2[0]) 
Out[53]: astropy.table.column.Column 
 
In [54]: mylist_1[0] 
Out[54]: 'defocus' 
 
In [55]: mylist_2[0] 
Out[55]:  
<Column name='defocus' dtype='float32' length=9> 
 -0.3 
 -0.3 
 -0.3 
-0.26 
-0.26 
-0.26 
-0.22 
-0.22 
-0.22 

我期待这两行:

mylist_1 = [x for x in cols] 

和

mylist_2 = [cols[k] for k in range(len(cols))] 

会得到完全相同的结果(第二个不太优雅),但事实并非如此,正如您在上面的输出中看到的那样(mylist_1 仅包含列名称,而不包含列本身)。为什么会这样?关于我的“cols”对象,有什么我不太了解的地方吗?

感谢您的见解。

(我在尝试将我的表写入适合文件时遇到了这个问题 - 使用 astropy.io.fits - 这需要构建一个适当的列列表,这并不像人们预期的那么明显......)

请您参考如下方法:

astropy.table.table.TableColumns 对象(通过 columns 属性访问)是一个有序字典,而不是列表。这就是为什么 [x for x in cols] 给出了列名列表(与遍历普通字典相同,给出的是键,而不是值)。

为方便起见,它还支持索引访问和切片,如 col[0] 或 cols[1:3]。但是,即使它支持类似列表的访问,TableColumns 首先也是最重要的一个字典。

在PR #4394将添加一个新的 itercols() 方法,它将支持 cols_list = [x for x in t.itercols()]。