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

时间:2017-10-24 16:27:34

标签: python python-2.7 file numpy astropy

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

  

ValueError:列表初始化中的元素必须是Column或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
...      ...

2 个答案:

答案 0 :(得分:4)

我建议明确创建一个蒙面表,它可以在较短列的长度和位置上提供更大的灵活性:

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 "" ""

我认为可能还有一些选项可以自定义屏蔽值的输出,但我现在无法在文档中进行深入研究。

答案 1 :(得分:2)

我不确定astropy.table包是否支持生成具有不同长度列的表。

解决此问题的一种简单方法是重复只有一个元素的列中的值。

from astropy.table import Table
from astropy.io import ascii


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

table = Table([x, y, [propNum] * len(x), [inc] * len(x)], names=('x', 'y', 'propNum', 'inc'))

ascii.write(table, 'test4.dat')

导致:

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

同样,您可以扩展最后两列以包含您想要发出空行的任何字符串:

fillVal = 'NA'
propNum = [100] + [fillVal] * (len(x) - 1)
inc = [51.762] + [fillVal] * (len(x) - 1)

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

给出:

x y propNum inc
6512905 -1739743 100 51.762
6291646 2420707 NA NA
3667192 5656530 NA NA
-358003 6731751 NA NA
-4246455 5235671 NA NA
-6512905 1739743 NA NA
-6291646 -2420707 NA NA
-3667192 -5656530 NA NA
358003 -6731751 NA NA
4246455 -5235671 NA NA

请注意,这仅适用于第一行中缺少值的情况。如果是,您仍然可以使用这种方法进行一些修改 -