I have data encoded as a binary string, with a mix of data types.
As an example (real data is much larger),
data = b'l:\x00\x00\xc0\xff|:g\x8em\xbf}:\xceUq\xbf'
I am reading this into an numpy array:
buffer = np.frombuffer(np.array(data), dtype='B')
which gives
array([108, 58, 0, 0, 192, 255, 124, 58, 103, 142, 109, 191, 125,
58, 206, 85, 113, 191], dtype=uint8)
I need to change this to (np.uint16, np.float), so the above array is
[(14956,NaN),(14972,-0.9280),(14973,-0.9427)]
I can use view for a single data type, e.g.
buffer.view(dtype=np.uint16) gives
array([14956, 0, 65472, 14972, 36455, 49005, 14973, 21966, 49009], dtype=uint16)
However don't think I can use a combination of data types for view like this. I have tried reshaping and slicing this,
buffer = buffer.reshape((3,-1))
firstData = buffer[:,:2]
firstData = array([[108, 58],
[124, 58],
[125, 58]], dtype=uint8)
firstData.view(dtype = np.uint16)
ValueError: new type not compatible with array.
As hinted in the documentation, this can be resolved by copying
firstData = firstData.copy()
firstData.view(dtype=np.uint16)
array([[14956],
[14972],
[14973]], dtype=uint16)
Is there a fast way to do this without copying the array?