Python Program to Copy an Array

Write a Python Program to copy the Numpy Array to another. In this programming language, we can use the equals operator to copy the complete Numpy Array to another.

import numpy as np

cparr = np.array([10, 20, 30, 40, 50])

copyarr = cparr

print("***Numpy Arrya Copy Result***")
print("Original Array = ", cparr)
print("Copied Array   = ", copyarr)

Output

***Numpy Arrya Copy Result***
Original Array =  [10 20 30 40 50]
Copied Array   =  [10 20 30 40 50]

Python Program to Copy an Array using = opertaor

In this Python example, we used the Python Tuple slicing technique to copy the required items to another NumPy array in Python.

import numpy as np

cparr = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90])

copyarr1 = cparr
copyarr2 = cparr[2:7]
copyarr3 = cparr[3:]
copyarr4 = cparr[::-1]

print("***Numpy Arrya Index Copy Result by Slicing***")
print("Original Array = ", cparr)
print("Copied Array   = ", copyarr1)
print("Copy Array from 2 to 7   = ", copyarr2)
print("Copy Array from 3 to End   = ", copyarr3)
print("Reverse Array   = ", copyarr4)
Python Program to Copy an Array 2

The below mentioned Program will Copy an Array using the For Loop range.

import numpy as np

cparr = np.array([12, 22, 35, 55, 47])
copyarr = np.empty(5)

for i in range(len(cparr)):
    copyarr[i] = cparr[i]

print("***Numpy Arrya Copy Result***")
print("Original Array = ", cparr)
print("Copied Array   = ", copyarr)

using for loop output

***Numpy Arrya Copy Result***
Original Array =  [12 22 35 55 47]
Copied Array   =  [12. 22. 35. 55. 47.]

When we use the = operator, it does not actually shallow copy an array into a new one. Instead, it creates a new variable referencing the old array. So, any changes will be reflected in the other. Refer to Python assignment operators.

from numpy import array
a = array([10, 25, 50, 75, 100])
b = a
print(id(a), " and ", id(b))
b[2] = 999
print(a)
print(b)
2831725554896  and  2831725554896
[ 10  25 999  75 100]
[ 10  25 999  75 100]

Program to copy an array using a view()

The built-in view() function creates a shallow copy of the original array, but it shares a reference to the original array elements. Its address may change, but they both share the same elements. If we make a change in one array, it reflects in the other.

from numpy import array
a = array([10, 25, 50, 75, 100])
b = a.view()
a[3] = 777
b[2] = 999
print(a)
print(b)
[ 10  25 999 777 100]
[ 10  25 999 777 100]

Program to deep copy an array

This program uses a built-in NumPy module copy() method that creates an independent copy. We can work independently, and changes won’t reflect.

from numpy import array
a = array([10, 25, 50, 75, 100])
b = a.copy()
a[3] = 777
b[2] = 999
print(a)
print(b)
[ 10  25  50 777 100]
[ 10  25 999  75 100]

Also Read