Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting from numpy array of one type to another by re-interpreting raw bytes

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.)

like image 448
Jason S Avatar asked Mar 25 '14 00:03

Jason S


People also ask

How do I change the Dtype of a numpy array?

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 a numpy array hold data of different data types?

Can an array store different data types? Yes, a numpy array can store different data String, Integer, Complex, Float, Boolean.

Can you reverse numpy array?

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.


1 Answers

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)
like image 104
unutbu Avatar answered Oct 24 '22 10:10

unutbu