python-3.x - 如何使用 Numpy .tobytes() 序列化对象
问题描述
你如何序列化/反序列化一个 numpy 数组?
A = np.random.randint(0, 10, 40).reshape(8, 5)
print(A)
print (A.dtype)
snapshot = A
serialized = snapshot.tobytes()
[[9 5 5 7 4]
[3 8 8 1 0]
[5 7 1 0 2]
[2 2 7 1 2]
[2 6 3 5 4]
[7 5 4 8 3]
[2 4 2 4 7]
[3 4 2 6 2]]
int64
退货
deserialized = np.frombuffer(serialized).astype(np.int64)
print (deserialized)
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0]
解决方案
dtype
用于生成的默认值A
与np.frombuffer
. 使用正确的 dtype 时按预期工作(可能取决于机器/Python/numpy 版本):
# Python 3.6 64-bits with numpy 1.12.1 64-bits
A = np.random.randint(0, 10, 40).reshape(8, 5)
print(A)
>>> array([[3, 3, 5, 3, 9],
[1, 4, 7, 1, 8],
[1, 7, 4, 3, 0],
[9, 2, 9, 1, 2],
[2, 8, 9, 1, 1],
[3, 3, 5, 2, 6],
[5, 0, 2, 7, 6],
[2, 8, 8, 0, 7]])
A.dtype
>>> dtype('int32')
deserialized = np.frombuffer(A.tobytes(), dtype=np.int32).reshape(A.shape)
print(deserialized)
>>> array([[3, 3, 5, 3, 9],
[1, 4, 7, 1, 8],
[1, 7, 4, 3, 0],
[9, 2, 9, 1, 2],
[2, 8, 9, 1, 1],
[3, 3, 5, 2, 6],
[5, 0, 2, 7, 6],
[2, 8, 8, 0, 7]])
推荐阅读
- python - Cython 函数指针和异常
- minecraft - 尝试使用 MCP 反编译 Minecraft 1.12 时出现巨大错误
- mule - Mule Requester 在打开文件时返回 org.mule.transport.AbstractConnector
- python - Python中类实例上的运算符()
- javascript - Cordova/Javascript 录音
- java - 在 Java 中设置两个不同 API 的 Classpath 的问题
- css - 有没有办法在网格项目之间共享背景?
- osgi - 如何在同一个插件中处理 2 个 OSGi 声明式服务包组件?
- c# - 生成 excel 文件时 NPOI 无法评估公式
- ios - 使用全色深度 MTLTextureDescriptor 创建 MTLTexture