Creating array views and copies

You might think that views means just to view something and nothing more, like the ravel() example on an array. In NumPy, views are NOT read-only!

That’s why, having a replica of the shared array view is very important. A slice of an array will produce a view; if you assign the slice to a variable and alter the underlying array then the value of the variable will change.

Example:

import scipy.misc 
import matplotlib.pyplot as plt

#Create an array from the face picture in the ScoPy package.
face = scipy.misc.face()

#Create a copy of the face array
acopy = face.copy()

#Create a view of the array
aview = face.view()

#Set all values to 0
aview.flat = 0

plt.subplot(221)
plt.imshow(face)
#out
<matplotlib.image.AxesImage at 0x7f1b727f2eb8>

plt.subplot(222)
plt.imshow(acopy)
#out
<matplotlib.image.AxesImage at 0x7f1b727aa710>

plt.subplot(223)
plt.imshow(aview)
#out
<matplotlib.image.AxesImage at 0x7f1b72776ef0>

plt.show()
#out

Creating array views and copies

Leave a Reply