792
In this article we will look at how to copy a numpy array to another array
Lets look at some examples
Example 1
First of all lets use the equals operator to copy the complete Numpy Array to another one.
import numpy as np originalarray = np.array([10, 20, 30, 40, 50]) copyarray = originalarray print("Original Array = ", originalarray) print("Copied Array = ", copyarray)
Lets run this and as expected you will see
>>> %Run numpyarraycopy1.py Original Array = [10 20 30 40 50] Copied Array = [10 20 30 40 50]
Example 2
Using a for loop with range
import numpy as np originalarray = np.array([12, 22, 35, 55, 47]) copyarray = np.empty(5) for i in range(len(originalarray)): copyarray[i] = originalarray[i] print("Original Array = ", originalarray) print("Copy Of Array = ", copyarray)
This is what you will get when you run this example
>>> %Run numpyarraycopy2.py Original Array = [10 20 30 40 50] Copy Of Array = [10. 20. 30. 40. 50.]
Example 3
import numpy as np originalarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) copyarray1 = originalarray copyarray2 = originalarray[3:7] copyarray3 = originalarray[4:] copyarray4 = originalarray[::-1] print("Original Array = ", originalarray) print("Copied Array = ", copyarray1) print("Copy Array Items 4 to 7 = ", copyarray2) print("Copy Array Items 5 to End = ", copyarray3) print("Reverse Array = ", copyarray4)
This is what you will get when you run this example
>>> %Run numpyarraycopy3.py Original Array = [ 1 2 3 4 5 6 7 8 9 10] Copied Array = [ 1 2 3 4 5 6 7 8 9 10] Copy Array Items 4 to 7 = [4 5 6 7] Copy Array Items 5 to End = [ 5 6 7 8 9 10] Reverse Array = [10 9 8 7 6 5 4 3 2 1]
Links
The examples are on github
They are called numpyarraycopy1, numpyarraycopy2 and numpyarraycopy3