In this article, we are going to learn about the copy() function and we will learn how this does the deep copy of the arrays.NumPy provides the copy() function which makes a complete copy of the array and its elements. The new array which gets created as copy doesn’t share the Data elements with the original array.
So let us understand the copy() function and its applications in NumPy.
First of all we will create an array that we will use for our demonstration.
import numpy as np players = np.array(["Sachin","Dravid","Dhoni","Kohli","Rohit","Yuvi"]) Team = players.copy() print("New Array after as copy of players:",Team) print("Original players array:",players)
We now will use the copy function to create a deep copy of the players’ array. So we will get a new Team array.
New Array after as copy of players: ['Sachin' 'Dravid' 'Dhoni' 'Kohli' 'Rohit' 'Yuvi'] Original players array: ['Sachin' 'Dravid' 'Dhoni' 'Kohli' 'Rohit' 'Yuvi']
Now let us verify that this new array is the same as the original array if we compare this with the Original players’ array by using ‘is’
print(Team is players)
Also, we can make use of the base attribute to verify that the new array does not share data with the original array and it have its own copy of data.
print(Team.base is players)
If we try to change the new array data then, does it affect the original array data?
The answer is No since we already saw above that each array now holds its own data and they do not share anything with each other.
Just to confirm our understanding let us jump to our next example which validates this point for us.
Here we are going to make a change in the data elements of Team array.
Team = "Sehwag" print("New Data in Team array",Team) print("Original array data elemnets",players)
New Data in Team array ['Sehwag' 'Dravid' 'Dhoni' 'Kohli' 'Rohit' 'Yuvi'] Original array data elemnets ['Sachin' 'Dravid' 'Dhoni' 'Kohli' 'Rohit' 'Yuvi']
As we can see from the output there is no impact on the original array when we changed the Team array data. This proves that they do not share any data.
The next item which we should check is, If there is any impact on the dimensions of the original array if we change the dimensions of the new array.We can verify the behavior by changing the new array dimensions like we are in the example below:
Team.shape = 3,2 print("New Shape of Team: ",Team) print("Shape of Original players: ",players)
New Shape of Team: [['Sehwag' 'Dravid'] ['Dhoni' 'Kohli'] ['Rohit' 'Yuvi']] Shape of Original players: ['Sachin' 'Dravid' 'Dhoni' 'Kohli' 'Rohit' 'Yuvi']
From the output above we can see that there is no change in the original array dimensions and it is still a linear array. So this confirms that there is no dimensions change when we change Team array dimensions.