You can convert a numpy array to bytes using .tobytes() function.
How do decode it back from this bytes array to numpy array? I tried like this for array i of shape (28,28)
>>k=i.tobytes()
>>np.frombuffer(k)==i
False
also tried with uint8 as well.
numpy.ndarray.tobytes () function construct Python bytes containing the raw data bytes in the array. order : [ {‘C’, ‘F’, None}, optional] Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array.
Numpy ndarray.tobytes () function | Python Last Updated : 22 Apr, 2020 numpy.ndarray.tobytes () function construct Python bytes containing the raw data bytes in the array. Syntax : numpy.ndarray.tobytes (order=’C’)
numpy.ndarray.tobytes () function construct Python bytes containing the raw data bytes in the array. order : [ {‘C’, ‘F’, None}, optional] Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array. Return : Python bytes exhibiting a copy of arr’s raw data.
As you can see, the DataFrame is now converted to a NumPy array: Alternatively, you can use the second approach of df.values to convert the DataFrame to a NumPy array: You’ll get the same NumPy array:
A couple of issues with what you're doing:
frombuffer will always interpret the input as a 1-dimensional array. It's the first line of the documentation. So you'd have to reshape to be (28, 28).
The default dtype is float. So if you didn't serialize out floats, then you'll have to specify the dtype manually (a priori no one can tell what a stream of bytes means: you have to say what they represent).
If you want to make sure the arrays are equal, you have to use np.array_equal. Using == will do an elementwise operation, and return a numpy array of bools (this presumably isn't what you want).
How do decode it back from this bytes array to numpy array?
Example:
In [3]: i = np.arange(28*28).reshape(28, 28) In [4]: k = i.tobytes() In [5]: y = np.frombuffer(k, dtype=i.dtype) In [6]: y.shape Out[6]: (784,) In [7]: np.array_equal(y.reshape(28, 28), i) Out[7]: True HTH.
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