Copies and views

A view on a NumPy array is just a particular way of portraying the data it contains. Creating a view does not result in a new copy of the array, rather the data it contains may be arranged in a specific order, or only certain data rows may be shown. Thus, if data is replaced on the underlying array's data, this will be reflected in the view whenever the data is accessed via indexing.

The initial array is not copied into the memory during slicing and is thus more efficient. The np.may_share_memory method can be used to see whether two arrays share the same memory block. However, it should be used with caution as it may produce false positives. Modifying a view modifies the original array:

    In [118]:ar1=np.arange(12); ar1
    Out[118]:array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
    
    In [119]:ar2=ar1[::2]; ar2
    Out[119]: array([ 0,  2,  4,  6,  8, 10])
    
    In [120]: ar2[1]=-1; ar1
    Out[120]: array([ 0,  1, -1,  3,  4,  5,  6,  7,  8,  9, 10, 11])  

To force NumPy to copy an array, we use the np.copy function. As we can see in the following array, the original array remains unaffected when the copied array is modified:

    In [124]: ar=np.arange(8);ar
    Out[124]: array([0, 1, 2, 3, 4, 5, 6, 7])
    
    In [126]: arc=ar[:3].copy(); arc
    Out[126]: array([0, 1, 2])
    
    In [127]: arc[0]=-1; arc
    Out[127]: array([-1,  1,  2])
    
    In [128]: ar
    Out[128]: array([0, 1, 2, 3, 4, 5, 6, 7])
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset