将 numpy 数组序列化为 npz 字符串?

Serialize numpy arrays into an npz string?

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

Storing and loading numpy arrays as files

就是使用下面的:

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

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

您可以简单地将压缩数组保存到 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)