Skip to main content
 首页 » 编程设计

python之使用具有不同列长度的 ascii.write()

2025年05月04日17findumars

我想将几个值( float 和整数)和数组保存到一个文本文件中。我尝试使用 astropy 表和 ascii.write() 但出现值错误。

ValueError: Elements in list initialization must be either Column or list-like

代码:

from astropy.table import Table 
from astropy.io import ascii 
 
table = Table([x, y, propNum, inc], names=('x', 'y', 'propNum', 'inc')) 
 
ascii.write(table, 'test4.dat') 

输入:

x = [6512905, 6291646, 3667192, -358003, -4246455, -6512905, -6291646,  -3667192, 358003, 4246455] 
y = [-1739743, 2420707, 5656530, 6731751, 5235671, 1739743, -2420707, -5656530, -6731751, -5235671] 
propNum = 100 
inc = 51.762 

期望的输出:

6512905, -1739743, 100, 51.762 
6291646, 2420707 
3667192, 5656530 
...      ... 

请您参考如下方法:

我建议明确创建一个屏蔽表,它在较短列的长度和位置方面提供更大的灵 active :

x = [6512905, 6291646, 3667192, -358003, -4246455, -6512905, -6291646,  -3667192, 358003, 4246455] 
y = [-1739743, 2420707, 5656530, 6731751, 5235671, 1739743, -2420707, -5656530, -6731751, -5235671] 
propNum = np.concatenate([[100], np.zeros(len(x)-1, dtype='i')]) 
inc = np.concatenate([[51.762], np.zeros(len(x)-1)]) 
 
mtab = Table([x, y, propNum, inc], names=('x', 'y', 'propNum', 'inc'), masked=True) 
mtab['propNum'][1:].mask = True 
mtab['inc'][1:].mask = True 
mtab.write('/dev/stdout', format='ascii', overwrite=True) 
 
x y propNum inc 
6512905 -1739743 100 51.762 
6291646 2420707 "" "" 
3667192 5656530 "" "" 
-358003 6731751 "" "" 
-4246455 5235671 "" "" 
-6512905 1739743 "" "" 
-6291646 -2420707 "" "" 
-3667192 -5656530 "" "" 
358003 -6731751 "" "" 
4246455 -5235671 "" "" 

我认为可能还有自定义掩码值输出的选项,但我现在无法在文档中挖掘它。