【问题标题】:Serialize numpy arrays into an npz string?将numpy数组序列化为npz字符串?
【发布时间】:2015-06-14 17:18:57
【问题描述】:

我正在寻找一种从多个具有不同类型的 numpy 数组中生成压缩二进制字符串的方法。 :D 本题推荐的方法:

Storing and loading numpy arrays as files

是用下面的:

np.savez_compressed('file_name_here.npz', arr_a = a, arr_b = b)

但需要注意的是,我直接需要实际的字符串,并且没有将其保存到的路径。有没有简单的方法可以直接生成二进制字符串而不保存到磁盘?有什么办法可以解决这个问题吗?

【问题讨论】:

  • 在旁注中,在文档中它说If keyword arguments are given, then filenames are taken from the keywords. If arguments are passed in with no keywords, then stored file names are arr_0, arr_1, etc.,为什么当 savez 应该保存单个文件时它会提到文件名?
  • savez... 将数据写入一组文件,每个变量都有一个不同的文件。这些被打包成一个档案,也可以被压缩。这不是为创建字符串缓冲区而设计的。

标签: python numpy io


【解决方案1】:

您可以简单地将压缩数组保存到 StringIO 对象并读回,

from cStringIO import StringIO
import numpy as np

x = np.ones(10)

f = StringIO()
np.savez_compressed(f, x=x)
f.seek(0)
out = f.read()

print(out)

【讨论】:

  • 所以np.load(StringIO(out))['x'] 将恢复x
  • 非常感谢@hpaulj
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 2016-05-13
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多