据我所知,你确实需要一个定制的循环“分铸”。在
事实上,NumPy可以读取像您这样的嵌套结构,但它们必须具有固定的形状,如Innumpy.loadtxt('data.txt', dtype=[ ('time', np.uint64), ('pos', [('x', np.float), ('y', np.float)]) ])
尝试使用所需的数据类型读取数据时,NumPy只读取每个元组的第一个数字:
^{pr2}$
因此打印[(9998, 1, 1, 128, '10097')
(9999, 1, 1, 128, '10098')
(10000, 1, 1, 128, '10099')…]
所以,我会说继续使用for循环,而不是numpy.loadtxt()。在
您还可以使用一种可能更快的中间方法:让NumPy用上述代码加载文件,然后手动“更正”N字段:dt=[('E', '
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))]