TheCodeCache
TheCodeCache

Reputation: 972

How does NumPy ndarrary.view(...) work internally

I've used the following code to create a view but i want to understand how this view works under the hood,

>>> x = np.array([(1, 2)], dtype=np.int8)
>>> y = x.view(dtype=np.int16)

where to find the source code for ndarray.view(...), I searched through the GitHub code repository but couldn't find it

Upvotes: 1

Views: 67

Answers (1)

hpaulj
hpaulj

Reputation: 231615

What are you most interested in - the coding mechanics, or how int8 values are repsented as int16?

view creates a new array, with its own shape and dtype, but sharing the data buffer with the source. Most of the code that you'll see has to do with creating that new array, with little to nothing about the specific dtypes.

There are actually two versions of int16, big-ended and little.

In [194]: np.array([(1,2)],np.int8).view('<i2')                                 
Out[194]: array([[513]], dtype=int16)
In [195]: np.array([(1,2)],np.int8).view('>i2')                                 
Out[195]: array([[258]], dtype=int16)

np.int8 is a single byte which can represent values up to 256. The values we see depend on how the 2 bytes are combined into 1 number.

In [197]: 2*256+1                                                               
Out[197]: 513
In [198]: 1*256+2                                                               
Out[198]: 258

My guess is that you won't see this level of detail in the numpy C code. It's performed by the C compiler.

Upvotes: 2

Related Questions