首页 > 解决方案 > 如何使用 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]

标签: python-3.xnumpyserialization

解决方案


dtype用于生成的默认值Anp.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]])

推荐阅读