python - 将给定格式说明符的表数据(卡片图像)读取到 Python 中

标签 python numpy pandas io astropy

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

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

问题在于列之间没有明确的分隔符/定界符,因此对于某些行,两列之间没有空格,如下所示:

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

网页上说这些被称为“卡片图像”。表格式信息描述如下:

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')

有人知道如何使用给定的每列的格式规范将该表读入 Python 中吗?

最佳答案

您可以在 Astropy 中使用固定宽度的阅读器。请参阅: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

关于python - 将给定格式说明符的表数据(卡片图像)读取到 Python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35018200/

相关文章:

python - MongoDB - 显示数据库中的所有文件

python - 如何使用 Python 中的返回计算最大亏损

python - 使用 scikit 决策树进行多输出分类

python - 无法升级我的 pip 版本。我的设置有问题

python - 分别对 numpy 数组中的所有偶数列和奇数列求和

python - np.ascontiguousarray 与 np.asarray 与 Cython

python - 用三角方法计算傅里叶级数

Python 请求 : Allow more retries

python - 将列值与行切片中的 n 行值进行比较

Python input() 给出未定义