Numpy practical examples
import numpy as npCopies and views¶
Let’s start by creating a numpy array :
x = np.arange(10)
display(x)array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])then create a view :
y = x[1:3]
display(y)array([1, 2])and modify the view :
y[:] = [10, 11]
display(y)array([10, 11])The array x is also modified :
display(x)array([ 0, 10, 11, 3, 4, 5, 6, 7, 8, 9])You can check if y is a view by reading the value of the ndarray.base attribute. The base attribute of a view returns the original array :
display(y.base)array([ 0, 10, 11, 3, 4, 5, 6, 7, 8, 9])If the array has its own memory, as is the case for independently created arrays, ndarray.base will be None.
display(x.base)NoneBe careful to the syntax when you modify the view, if you omit square bracket, you create a new object :
y = [12, 14]
display(y)[12, 14]and the array x is not modified :
display(x)array([ 0, 10, 11, 3, 4, 5, 6, 7, 8, 9])The y object is now a list :
display(type(y))list