簡體   English   中英

將1D numpy數組追加到文件中,並在新行中添加新元素

[英]Append 1D numpy array to file with new element in new line

我有許多迭代生成的numpy數組。 我想將每個數組保存到一個文件。 然后,我生成下一個數組並將其附加到文件中,依此類推(如果我一口氣做到了,那么我將使用過多的內存)。 我最好怎么做? 有沒有辦法讓我們使用numpy函數,例如numpy.savetxt (我找不到該功能的附加選項。)

我當前的代碼是:

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')

您可以將打開的文件(句柄)傳遞給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是您提供的字符串,或者是復制的字符串以匹配數組中的列數。

我建議使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM