HippoMan
HippoMan

Reputation: 2308

Converting back to ndarray from a previous ndarray.tobytes()?

When using numpy, suppose that I have an arbitrary, previously created ndarray called my_ndarray. I want to be able to do the following, if possible ...

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

Is there any way to deserialize something that was specifically created via tobytes() back to a meaningful ndarray?

Or am I stuck having to use some other form of serialization/deserialization?

Upvotes: 5

Views: 4433

Answers (1)

cs95
cs95

Reputation: 402293

You can use np.frombuffer:

new_ndarray = np.frombuffer(my_bytes)

Demo (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])

Upvotes: 8

Related Questions