2

我需要将一个 ASCII 文件读入 Python,该文件的摘录如下所示:

E     M S T   N...
...
9998  1 1 128 10097 10098 10199 10198 20298 20299 20400 20399
9999  1 1 128 10098 10099 10200 10199 20299 20300 20401 20400
10000 1 1 128 10099 10100 10201 10200 20300 20301 20402 20401
10001 1 2  44  2071  2172 12373 12272
10002 1 2  44  2172  2273 12474 12373

理想情况下,上述内容应遵循 NumPy 模式:

array([(9998, 1, 1, 128, (10097, 10098, 10199, 10198, 20298, 20299, 20400, 20399)),
       (9999, 1, 1, 128, (10098, 10099, 10200, 10199, 20299, 20300, 20401, 20400)),
       (10000, 1, 1, 128, (10099, 10100, 10201, 10200, 20300, 20301, 20402, 20401)),
       (10001, 1, 2, 44, (2071, 2172, 12373, 12272)),
       (10002, 1, 2, 44, (2172, 2273, 12474, 12373))], 
      dtype=[('E', '<i4'), ('M', '<i4'), ('S', '<i4'), ('T', '<i4'), ('N', '|O4')])

最后一个对象 ,Ntuple2 到 8 个整数的 a。

我想使用np.loadtxtor加载这个参差不齐的结构np.genfromtxt,但我不确定这是否可行。任何内置提示,还是我需要做一个自定义的 split-cast-for-loop?

4

1 回答 1

2

据我所知,您确实需要一个自定义的“split-cast” for 循环。

事实上,NumPy 可以读取像你这样的嵌套结构,但它们必须具有固定的形状,如

numpy.loadtxt('data.txt', dtype=[ ('time', np.uint64), ('pos', [('x', np.float), ('y', np.float)]) ])

当尝试使用所需的 dtype 读取数据时,NumPy 仅读取每个元组的第一个数字:

dt=[('E', '<i4'), ('M', '<i4'), ('S', '<i4'), ('T', '<i4'), ('N', '|O4')]
print numpy.loadtxt('data.txt', dtype=dt)

因此打印

[(9998, 1, 1, 128, '10097')
 (9999, 1, 1, 128, '10098')
 (10000, 1, 1, 128, '10099')…]

所以,我会说继续使用 for 循环而不是numpy.loadtxt().

您也可以使用一种可能更快的中间方法:让 NumPy 使用上述代码加载文件,然后手动“更正”“N”字段:

dt=[('E', '<i4'), ('M', '<i4'), ('S', '<i4'), ('T', '<i4'), ('N', '|O4')]
arr = numpy.loadtxt('data.txt', dtype=dt)  # Correctly reads the first 4 columns

with open('data.txt') as input_file:
    for (line_num, line) in enumerate(input_file):
        arr[line_num]['N'] = tuple(int(x) for x in line.split()[4:])  # Manual setting of the tuple column

这种方法可能比在 for 循环中解析整个数组更快。这会产生您想要的结果:

[(9998, 1, 1, 128, (10097, 10098, 10199, 10198, 20298, 20299, 20400, 20399))
 (9999, 1, 1, 128, (10098, 10099, 10200, 10199, 20299, 20300, 20401, 20400))
 (10000, 1, 1, 128, (10099, 10100, 10201, 10200, 20300, 20301, 20402, 20401))
 (10001, 1, 2, 44, (2071, 2172, 12373, 12272))
 (10002, 1, 2, 44, (2172, 2273, 12474, 1237))]
于 2011-04-14T09:33:06.627 回答