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?
Construct Python bytes containing the raw data bytes in the array. Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object can be produced in either 'C' or 'Fortran', or 'Any' order (the default is 'C'-order).
tobytes() function returns the binary representation of the given array.
To convert a NumPy array (ndarray) to a Python list use ndarray. tolist() function, this doesn't take any parameters and returns a python list for an array. While converting to a list, it converts the items to the nearest compatible built-in Python type.
numpy. string_ is the NumPy datatype used for arrays containing fixed-width byte strings. On the other hand, str is a native Python type and can not be used as a datatype for NumPy arrays*.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With