使用numpy的genfromtxt读取每N行的最快方法

3
我使用numpy的genfromtxt读取数据:
import numpy as np
measurement = np.genfromtxt('measurementProfile2.txt', delimiter=None, dtype=None, skip_header=4, skip_footer=2, usecols=(3,0,2))
rows, columns = np.shape(measurement)
x=np.zeros((rows, 1), dtype=measurement.dtype)
x[:]=394
measurement = np.hstack((measurement, x))
np.savetxt('measurementProfileFormatted.txt',measurement)

这个可以正常运行。但我只想在最终的输出文件中保留第五和第六行(以及其他行)。根据 numpy.genfromtxt.html ,没有参数可以做到这一点。我不想遍历数组。有没有推荐的处理方法?
3个回答

4
为避免读取整个数组,可以将np.genfromtxtitertools.islice相结合以跳过行。对于我尝试过的较小的数组来说,这比先读取整个数组再进行切片略快一些。
例如,这是file.txt的内容:
12
34
22
17
41
28
62
71

例如,接下来就是一个例子:
>>> import itertools
>>> with open('file.txt') as f_in:
        x = np.genfromtxt(itertools.islice(f_in, 0, None, 3), dtype=int)

返回一个数组x,其中包含上述文件的索引为036的元素:

array([12, 17, 62])

我喜欢这个比@elyase的更好。我觉得它更符合Python的风格。 - user69453
是的,这就是正确的解决方案。我考虑过,但没有测试,认为它会更慢。 - elyase
genfromtxt 可以接受任何提供给它的行——文件、行列表、生成器等。之前有一些类似的 SO 问题:通过行过滤器传递文件。 - hpaulj
很多人建议在阅读后进行切片,但是在我的情况下,阅读肯定是慢的。这对我帮助很大! - delrocco

0

无论如何,您都必须读取整个文件,要选择第n个元素,请执行以下操作:

>>> a = np.arange(50)
>>> a[::5]
array([ 0,  5, 10, 15, 20, 25, 30, 35, 40, 45])

0

如果您只想在最终输出文件中保留特定行,为什么不仅保存这些行而不是保存整个“measurement”矩阵呢:

output_rows = [5,7,11]
np.savetxt('measurementProfileFormatted.txt',measurement[output_rows,:])


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接