Categories: NumpyPython

Views and copy of Numpy array in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

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])

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago