Same as with Python lists, simply using equal symbol to assign an array to a new object will make two arrays referring to the same array. Unlike lists, in which slicing of a list returns an independent list, slicing a Numpy array is also a view of the original array. If you really want to create an independent array from the original one, you can use copy() function from Numpy module. Next example codes show these mechanisms.
#Import Numpy module
import numpy as np
#create an array of 6 elements
T1 = np.array([27, 28, 29,30,31,32])
T1
#output
array([27, 28, 29, 30, 31, 32])
#create a second array, using equal symbol to the first one
T2 = T1
T2
#output
array([27, 28, 29, 30, 31, 32])
#assign new value to the fourth element of the original array
T1[3] = 32
T1
#output
array([27, 28, 29, 32, 31, 32])
#show the second array, and its fourth element also changed
T2
array([27, 28, 29, 32, 31, 32])
#create a slice of the first to fourth elements of thefirst array
T3 = T1[0:4]
T3
#output
array([32, 28, 29, 32])
# modify the second element of the first array
#the slicing array also changed automatically
T1[1] =32
T1
#output
array([32, 32, 29, 32, 32, 32])
T3
#output
array([32, 32, 29, 32])
#using copy() function
T4 = T1.copy()
T4
#output
array([32, 32, 29, 32, 32, 32])
#modify the third element of the first array
T1[2] =32
T1
#output
array([32, 32, 32, 32, 32, 32])
#the copy of array not modified
T4
#output
array([32, 32, 29, 32, 32, 32])
0 Comments