MaskedArray.view(dtype=None,type=None)[source]¶New view of array with the same data.
| Parameters: |
|
|---|
Notes
a.view() is used two different ways:
a.view(some_dtype) ora.view(dtype=some_dtype) constructs a viewof the array’s memory with a different data-type. This can cause areinterpretation of the bytes of memory.
a.view(ndarray_subclass) ora.view(type=ndarray_subclass) justreturns an instance ofndarray_subclass that looks at the same array(same shape, dtype, etc.) This does not cause a reinterpretation of thememory.
Fora.view(some_dtype), ifsome_dtype has a different number ofbytes per entry than the previous dtype (for example, converting aregular array to a structured array), then the behavior of the viewcannot be predicted just from the superficial appearance ofa (shownbyprint(a)). It also depends on exactly howa is stored inmemory. Therefore ifa is C-ordered versus fortran-ordered, versusdefined as a slice or transpose, etc., the view may give differentresults.
Examples
>>>x=np.array([(1,2)],dtype=[('a',np.int8),('b',np.int8)])
Viewing array data using a different type and dtype:
>>>y=x.view(dtype=np.int16,type=np.matrix)>>>ymatrix([[513]], dtype=int16)>>>print(type(y))<class 'numpy.matrixlib.defmatrix.matrix'>
Creating a view on a structured array so it can be used in calculations
>>>x=np.array([(1,2),(3,4)],dtype=[('a',np.int8),('b',np.int8)])>>>xv=x.view(dtype=np.int8).reshape(-1,2)>>>xvarray([[1, 2], [3, 4]], dtype=int8)>>>xv.mean(0)array([ 2., 3.])
Making changes to the view changes the underlying array
>>>xv[0,1]=20>>>print(x)[(1, 20) (3, 4)]
Using a view to convert an array to a recarray:
>>>z=x.view(np.recarray)>>>z.aarray([1], dtype=int8)
Views share data:
>>>x[0]=(9,10)>>>z[0](9, 10)
Views that change the dtype size (bytes per entry) should normally beavoided on arrays defined by slices, transposes, fortran-ordering, etc.:
>>>x=np.array([[1,2,3],[4,5,6]],dtype=np.int16)>>>y=x[:,0:2]>>>yarray([[1, 2], [4, 5]], dtype=int16)>>>y.view(dtype=[('width',np.int16),('length',np.int16)])Traceback (most recent call last): File"<stdin>", line1, in<module>ValueError:new type not compatible with array.>>>z=y.copy()>>>z.view(dtype=[('width',np.int16),('length',np.int16)])array([[(1, 2)], [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')])