读取 table 数据(卡片图像),给定格式说明符,进入 Python

Reading table data (card images), with format specifier given, into Python

我正在尝试将 ascii-table 读入 Python 中的 Numpy/Pandas/Astropy array/dataframe/table。 table 中的每一行看起来像这样:

  329444.6949     0.0124    -6.0124 3   97.9459 15  32507 303 7 3 4       8 2 7          HDC-13-O

问题是列之间没有明确的separator/delimiter,所以对于某些行,两列之间没有space,像这样:

  332174.9289     0.0995    -6.3039 3 1708.1601219  30501 30336 333      37 136          H2CO

网页上说这些叫做 "card images"。 table格式的信息是这样描述的:

The catalog data files are composed of 80-character card images, with one card image per spectral line. The format of each card image is: FREQ, ERR, LGINT, DR, ELO, GUP, TAG, QNFMT, QN', QN" (F13.4,F8.4, F8.4, I2,F10.4, I3, I7, I4, 6I2, 6I2)

我非常想要一种只使用上面给出的格式说明符的方法。我唯一发现的是 Numpy 的 genfromtxt 函数。但是,以下不起作用。

np.genfromtxt('tablename', dtype='f13.4,f8.4,f8.4,i2,f10.4,i3,i7,i4,6i2,6i2')

任何人都知道如何使用给定的每一列的格式规范将此 table 读入 Python?

您可以在 Astropy 中使用 fixed-width reader。参见:http://astropy.readthedocs.org/en/latest/io/ascii/fixed_width_gallery.html#fixedwidthnoheader。这仍然需要您对列进行计数,但您可以为您显示的 dtype 表达式编写一个简单的解析器。

与上面的 pandas 解决方案(例如 df['FREQ'] = df.data.str[0:13])不同,这将自动确定列类型并根据您的情况给出 float 和 int 列。 pandas 版本导致所有 str 类型的列,这可能不是您想要的。

引用此处的文档示例:

>>> from astropy.io import ascii
>>> table = """
... #1       9        19                <== Column start indexes
... #|       |         |                <== Column start positions
... #<------><--------><------------->  <== Inferred column positions
...   John   555- 1234 192.168.1.10
...   Mary   555- 2134 192.168.1.123
...    Bob   555- 4527  192.168.1.9
...    Bill  555-9875  192.255.255.255
... """
>>> ascii.read(table,
...            format='fixed_width_no_header',
...            names=('Name', 'Phone', 'TCP'),
...            col_starts=(1, 9, 19),
...            )
<Table length=4>
Name   Phone         TCP
str4    str9        str15
---- --------- ---------------
John 555- 1234    192.168.1.10
Mary 555- 2134   192.168.1.123
 Bob 555- 4527     192.168.1.9
Bill  555-9875 192.255.255.255