1

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

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
TheCodeCache
  • 820
  • 1
  • 7
  • 27
  • 1
    https://github.com/numpy/numpy/blob/03c664f53be759ec9c890bd4b4e7e2d5687e7efc/numpy/core/src/multiarray/methods.c#L243 – Brad Solomon Mar 24 '19 at 14:28

1 Answers1

2

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Hi @hpaulj, thanks for the reply, basically i am trying to understand the mechanics behind numpy view(...) in general. just like array broadcasting is powered by multi iterators behind the scene, so is this view(...) also backed-up by some iterators or something else, I wanted to see some piece of source code to understand it or some blogs/forums that talks about the internals of how view(...) works under the cover. – TheCodeCache Mar 24 '19 at 18:40
  • how to get the view that can result the array having alternate elements from the original array, for ex:- array1 = np.array([1,2,3,4,5]) and array2 = array1.view() this gives me all the elements from the original array array1, but how to create a view having only alternate items form the original array, like [1,3,5], is there anyway to achieve using just numpy view(...) ?? – TheCodeCache Mar 24 '19 at 18:44
  • 1
    The `view` method isn't the only way to create a `view` :) Basic indexing, ie. with a slice, also creates a view: `arr[::2]`. The view method, as shown in its docs, has two purposes, changing `dtype` and changing subclass, `type`. – hpaulj Mar 24 '19 at 19:58