用numpy保存二进制二进制列

时间:2015-05-21 00:44:13

标签: file python-3.x numpy

我用

读了一些二进制列
dtype = ['<f8', '<f8', '<i4']
raw = np.fromfile(file_id, dtype=dtype, count=n_col)
f0 = raw[0]
f1 = raw[1]
i0 = raw[2]

现在我只有numpy数组f0f1i0。我将如何以相同的意义将它们写入二进制文件。它尝试了

np.array([f0, f1, i0]).tofile(file_id) # Promotes my int32 to double
np.array(tuple([f0, f1, i0]).tofile(file_id) # Does something writing a lot of data, but I have no idea in what structure

任何帮助都会受到欢迎。

1 个答案:

答案 0 :(得分:0)

我发现的一个可能的解决方案是首先将所有内容强制转换为一个int32的大块,然后将其写下来。由于我没有找到任何类型转换,我复制了整个内存。我正在做这样的事情:

raw = []
# Kind of make a very ugly typecast by using a lot of Memomory
tmp = np.fromstring(f0.tostring(), dtype=np.int32)
raw.append(tmp[::2])
raw.append(tmp[1::2])

... # do the same of f1

raw.append(i0)

# Finaly write it down
np.array(raw).transpose().tofile(file_id)

由于这个解决方案是非常丑陋的记忆,我不会接受它直到星期一。也许有人可以通过更好的解决方案帮助我。

相关问题