【发布时间】:2015-08-15 16:53:28
【问题描述】:
我正在尝试处理存储在一个类似于 test.dat 的文本文件中的数据:
-1411.85 2.6888 -2.09945 -0.495947 0.835799 0.215353 0.695579
-1411.72 2.82683 -0.135555 0.928033 -0.196493 -0.183131 -0.865999
-1412.53 0.379297 -1.00048 -0.654541 -0.0906588 0.401206 0.44239
-1409.59 -0.0794765 -2.68794 -0.84847 0.931357 -0.31156 0.552622
-1401.63 -0.0235102 -1.05206 0.065747 -0.106863 -0.177157 -0.549252
....
....
该文件有几个 GB,我非常想以小行的形式读取它。我想使用numpy'sloadtxt 函数,因为这会将所有内容快速转换为numpy array。但是,我无法管理,因为该功能似乎只提供了一些列,如下所示:
data = np.loadtxt("test.dat", delimiter=' ', skiprows=1, usecols=range(1,7))
任何想法如何实现这一目标?如果loadtxt 无法使用Python 中的任何其他选项?
【问题讨论】:
-
loadtxt 的 fname 参数可以是生成器,因此要读取小块行使用文件读取生成器,例如 nosklo 在stackoverflow.com/questions/519633/… 中的回答中所示,但转换为仅读取少量行而不是字节.
-
另见:stackoverflow.com/a/27962976/901925 -
Fastest way to read every n-th row with numpy's genfromtxt