如何从字节制作一个 numpy ndarray?

新手上路,请多包涵

我可以使用 myndarray.tobytes() 现在如何将它恢复为 ndarray?

使用 .tobytes() 方法文档中的示例:

 >>> x = np.array([[0, 1], [2, 3]])
>>> bytes = x.tobytes()
>>> bytes
b'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'

>>> np.some_magic_function_here(bytes)
array([[0, 1], [2, 3]])

原文由 Jonathan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 672
2 个回答

编辑后,您似乎走错了方向!

当只需要从这些字节重建时, 您不能使用 np.tobytes() 来存储包含所有信息(如形状和类型)的完整数组! 它只会保存 原始 数据(单元格值)并以 C 或 Fortran 顺序展平这些数据。

现在我们不知道你的任务。但是你需要一些基于 序列化 的东西。有很多方法,最简单的是以下基于 python 的 pickle 的方法(此处的示例:python3!):

 import pickle
import numpy as np

x = np.array([[0, 1], [2, 3]])
print(x)

x_as_bytes = pickle.dumps(x)
print(x_as_bytes)
print(type(x_as_bytes))

y = pickle.loads(x_as_bytes)
print(y)

输出:

 [[0 1]
 [2 3]]
 b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K\x02K\x02\x86q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00i8q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00<q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89C \x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00q\rtq\x0eb.'
<class 'bytes'>
[[0 1]
 [2 3]]

更好的选择是 joblib 的 pickle,它具有针对大型阵列的专门酸洗。 joblib 的函数是基于文件对象的,也可以使用 python 的 BytesIO 在内存中使用字节串。

原文由 sascha 发布,翻译遵循 CC BY-SA 3.0 许可协议

要反序列化您需要的字节 np.frombuffer()

tobytes() 将数组序列化为字节, np.frombuffer() 反序列化它们。

请记住,一旦序列化, 形状信息就会丢失,这意味着在反序列化之后,需要将其重塑回原来的形状。

下面是一个完整的例子:

 import numpy as np

x = np.array([[0, 1], [2, 3]], np.int8)
bytes = x.tobytes()
# bytes is a raw array, which means it contains no info regarding the shape of x
# let's make sure: we have 4 values with datatype=int8 (one byte per array's item), therefore the length of bytes should be 4bytes
assert len(bytes) == 4, "Ha??? Weird machine..."

deserialized_bytes = np.frombuffer(bytes, dtype=np.int8)
deserialized_x = np.reshape(deserialized_bytes, newshape=(2, 2))
assert np.array_equal(x, deserialized_x), "Deserialization failed..."

原文由 Daniel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题