如何从字节创建 numpy ndarray?

2024-03-06

我可以使用将 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]])

反序列化您需要的字节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..."
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从字节创建 numpy ndarray? 的相关文章

随机推荐