2016-09-30 183 views
0

我有一些我反复生成的numpy数组。我想将每个数组保存到一个文件中。然后我生成下一个数组,并将其附加到文件等等(如果我一次做了,我会使用太多的内存)。我最好怎么做?有没有办法让我们拥有诸如numpy.savetxt? (我无法找到该功能的附加选项。)追加1D numpy数组到新行中的新元素文件

我当前的代码是:

with open('paths.dat','w') as output: 
    for i in range(len(hist[0])): 
     amount = hist[0][i].astype(int) 
     array = hist[1][i] * np.ones(amount) 
     for value in array: 
      output.write(str(value)+'\n') 
+0

Python内置的文件读/写不会完成这个吗? – lucasnadalutti

+0

是的,当然,我想知道是否有更高效的numpy方式。现在我正在编辑我的文章。 –

+0

@ P-M为什么将它们保存在同一个文件中非常重要? – MZHm

回答

1

你可以打开的文件(句柄)传递给savetxt

with open('paths.dat','w') as output: 
    for i in range(len(hist[0])): 
     amount = hist[0][i].astype(int) 
     myArray = hist[1][i] * np.ones(amount) 
     np.savetxt(output, myArray, delimiter=',', fmt='%10f') 

np.savetxt如果指定了名称,将打开该文件,否则使用该文件。

在阵列的行然后进行迭代,并且将它们写入

for row in myArray: 
    f.write(fmt % tuple(row)) 

其中fmt是你给的字符串,或者被复制到匹配数组中的列数之一。

0

我会建议使用HDF5。它们对IO来说非常快。 这里是你如何写你的数据:

import numpy as np 
import tables 

fname = 'myOutput.h5' 
length = 100 # your data length 
my_data_generator = xrange(length) # Your data comes here instead of the xrange 

filters = tables.Filters(complib='blosc', complevel=5) # you could change these 
h5file = tables.open_file(fname, mode='w', title='yourTitle', filters=filters) 
group = h5file.create_group(h5file.root, 'MyData', 'MyData') 
x_atom = tables.Float32Atom() 

x = h5file.create_carray(group, 'X', atom=x_atom, title='myTitle', 
         shape=(length,), filters=filters) 

# this is a basic example. It will be faster if you write it in larger chunks in your real code 
# like x[start1:end1] = elements[start2:end2] 
for element_i, element in enumerate(my_data_generator): 
    x[element_i] = element 
    h5file.flush() 

h5file.close() 

对于阅读它使用:

h5file = tables.open_file(fname, mode='r') 
x = h5file.get_node('/MyData/X') 
print x[:10] 

结果:

marray([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)