Is there any way to do a "reinterpret_cast" with numpy arrays? Here's an example:
>>> import numpy as np
>>> x=np.array([105,79,196,53,151,176,59,202,249,0,207,6], dtype=np.uint8)
>>> np.fromstring(x.tostring(),'<h')
array([ 20329, 13764, -20329, -13765, 249, 1743], dtype=int16)
I can call tostring()
and then fromstring()
to convert from an array to raw bytes and then back to another array. I'm just wondering if there's a way for me to skip the intermediate step. (not that it's a big deal, I would just like to understand.)
We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array.
Can an array store different data types? Yes, a numpy array can store different data String, Integer, Complex, Float, Boolean.
For this, we can easily use the function numpy. flip(). This method reverses the order of given array elements along the axis, preserving the shape of the array.
Yes. When you view an array with a different dtype, you are reinterpreting the underlying data (zeros and ones) according to the different dtype.
In [85]: x.view('<i2')
Out[85]: array([ 20329, 13764, -20329, -13765, 249, 1743], dtype=int16)
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