Today we’ll learn how to copy a numpy array.
If you want to copy an array, you can use either the numpy.copy method or the ndarray.copy method directly on the array.
Here’s an example with the former. Let’s create an array and reshape it to have 7 rows and 5 columns:
>>> a = np.arange(1, 36).reshape(7, 5)
>>> print(a)
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]]
Let’s make a copy:
>>> b = np.copy(a)
>>> print(b)
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]]
Now let’s modify array a. Let’s set all the elements in it to 10.
>>> a[0] = 10
>>> print(a)
[[10 10 10 10 10]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]]
Let’s see whether the copy is still as before:
>>> print(b)
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]]
And now let’s see how the other method can be used. Let’s copy the array b:
>>> c = b.copy()
>>> print(c)
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]]
And now let’s modify b:
>>> b[-1, -1] = 100
>>> print(b)
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[ 11 12 13 14 15]
[ 16 17 18 19 20]
[ 21 22 23 24 25]
[ 26 27 28 29 30]
[ 31 32 33 34 100]]
So, what does the array c look like now?
>>> print(c)
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]]
Here’s the video version of this article: