看着source https://github.com/numpy/numpy/blob/v1.8.1/numpy/lib/npyio.py#L628, 看起来numpy.loadtxt
包含大量代码来处理许多不同的格式。如果您有一个定义良好的输入文件,那么编写针对您的特定文件格式优化的自己的函数并不太困难。像这样的东西(未经测试):
def load_big_file(fname):
'''only works for well-formed text file of space-separated doubles'''
rows = [] # unknown number of lines, so use list
with open(fname) as f:
for line in f:
line = [float(s) for s in line.split()]
rows.append(np.array(line, dtype = np.double))
return np.vstack(rows) # convert list of vectors to array
如果之前已知行数和列数,则另一种解决方案可能是:
def load_known_size(fname, nrow, ncol)
x = np.empty((nrow, ncol), dtype = np.double)
with open(fname) as f:
for irow, line in enumerate(f):
for icol, s in enumerate(line.split()):
x[irow, icol] = float(s)
return x
这样,您就不必分配所有中间列表。
EDIT:似乎第二个解决方案有点慢,列表理解可能比显式 for 循环更快。结合这两种解决方案,并使用 Numpy 进行从字符串到浮点数的隐式转换的技巧(刚刚发现),这可能会更快:
def load_known_size(fname, nrow, ncol)
x = np.empty((nrow, ncol), dtype = np.double)
with open(fname) as f:
for irow, line in enumerate(f):
x[irow, :] = line.split()
return x
为了获得进一步的加速,您可能必须使用一些用 C 或 Cython 编写的代码。我很想知道这些函数打开您的文件需要多长时间。