O'Reilly logo

NumPy Cookbook - Second Edition by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating views and copies

It is important to know when we are dealing with a shared array view, and when we have a copy of the array data. A slice, for instance, will create a view. This means that if you assign the slice to a variable and then change the underlying array, the value of this variable will change. We will create an array from the famous Lena image, copy the array, create a view, and at the end, modify the view.

Getting ready

The prerequisites are the same as those for the previous recipe.

How to do it...

Let's create a copy and views of the Lena array:

  1. Create a copy of the Lena array:
    acopy = lena.copy()
    
  2. Create a view of the array:
    aview = lena.view()
    
  3. Set all the values of the view to 0 with a flat iterator:
    aview.flat = 0
    

    The end result ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required