从之前的ndarray.tobytes()转换回ndarray?

时间:2017-06-24 18:37:41

标签: python numpy byte deserialization

使用numpy时,假设我有一个名为ndarray的任意,之前创建的my_ndarray。如果可能,我希望能够做到以下几点......

my_bytes = my_ndarray.tobytes()
new_ndarray = ## ... somehow convert `my_bytes` back to a `nympy.ndarray`
## ... such that `my_ndarray` and `new_ndarray` are equal
assert(numpy.equal(my_ndarray, new_ndarray)) # I expect this to succeed

有没有办法将通过tobytes()创建的 的内容反序列化为有意义的ndarray

还是我不得不使用其他形式的序列化/反序列化?

1 个答案:

答案 0 :(得分:3)

您可以使用np.frombuffer

new_ndarray = np.frombuffer(my_bytes)

演示(python2):

>>> x = np.random.randn(10)
>>> my_bytes = x.tobytes()
>>> my_bytes
b'\x8d\x10\xfe\x1e\xaa^\xa0\xbfw\xa26\xca\xbc\xb1\xf5\xbf\x06(C\xe4\x9d\xb9\xae?\xed9\x170rZ\xe9?\x1c\x99\xd5TQ\xbe\xc5\xbfk\xd42\xb3(\xbb\xf3\xbf\xc7K.L\x1fu\xe5\xbfHE\xc2H~\xca\xdd\xbf\xe79\xdfJ\xeec\xf7\xbf\xe3\x9ds\x88\xbe\x1c\xf4\xbf' 
>>> np.frombuffer(my_bytes)
array([-0.03197223, -1.35589293,  0.06000989,  0.79229078, -0.16987054,
       -1.23319311, -0.67054715, -0.46548421, -1.46189718, -1.25701764])