When Converting To Tobytes() It Changes The Numpy Array. Valueerror: Expected 2d Array, Got 1d Array Instead:
I was doing this socket communication code to send inputs from the server.py (on the laptop) to the client.py (raspberry pi), in this communication I send from a 2d Numpy array a r
Solution 1:
tobytes
is just a byte copy of the array's data-buffer. It does not convey any dtype or shape information:
In [31]: x = np.arange(12).reshape((3,4))
In [32]: astr = x.tobytes()
In [33]: astr
Out[33]: b'\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x0...\x00\x00\x00'
According to the docs, the default load is as float64:
In [34]: y = np.frombuffer(astr)
In [35]: y
Out[35]:
array([0.0e+000, 4.9e-324, 9.9e-324, 1.5e-323, 2.0e-323, 2.5e-323,
3.0e-323, 3.5e-323, 4.0e-323, 4.4e-323, 4.9e-323, 5.4e-323])
correcting the dtype
In [36]: y = np.frombuffer(astr, dtype=int)
In [37]: y
Out[37]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
adding the shape:
In [38]: y.reshape((3,4))
Out[38]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
Post a Comment for "When Converting To Tobytes() It Changes The Numpy Array. Valueerror: Expected 2d Array, Got 1d Array Instead:"