Python Numpy - Duplicate or Copy Array Data to Another Array


Python Numpy - Duplicate or Copy Array

You can copy a numpy array into another. Copying array means, a new instance is created, and the elements of the original array are copied into new array.

To copy array data to another using Python Numpy library, you can use numpy.ndarray.copy() function.

Syntax

Following is the syntax to make a copy of a numpy array into another array.

array2 = array1.copy()

where array1 is a numpy n-dimensional array. array1.copy() returns a new array but with the exact element values as that of array1.

Examples

1. Copy Array using numpy.copy()

In the following example, we will copy the elements of an array a to another array b.

Python Program

import numpy as np

# create a numpy array
a = np.array([[8, 2, 3],
              [4, 7, 6]])

# copy contents of a to b
b = a.copy()

# modify a
a[1, 2] = 13

# check if b has remained the same
print('a\n',a)
print('\nb\n',b)

Output

a
 [[ 8  2  3]
 [ 4  7 13]]

b
 [[8 2 3]
 [4 7 6]]

Even if we have changed the contents of a, the contents of b are unaffected.

2. What happens if we use assignment operator to copy array

This is a negative scenario. This example explains why you should use copy() function instead of assignment operator when you have to create a duplicate of an array.

Python Program

import numpy as np

# create a numpy array
a = np.array([[8, 2, 3],
              [4, 7, 6]])

# assign a to b
b = a

# modify a
a[1, 2] = 13

# check if b has remained the same
print('a\n',a)
print('\nb\n',b)

Output

a
 [[ 8  2  3]
 [ 4  7 13]]

b
 [[ 8  2  3]
 [ 4  7 13]]

b acts as a mere reference to a. And when you change a, then b also gets changed. Hence, using assignment operator is not a way to duplicate or copy a numpy array.

Summary

In this Numpy Tutorial of Python Examples, we learned how to copy a numpy array from one variable to another.