NumPy ndarray.copy() Method | Make Copy of a Array
Last Updated :
05 Feb, 2024
Improve
The ndarray.copy() method returns a copy of the array.
It is used to create a new array that is a copy of an existing array but does not share memory with it. This means that making any changes to the original array won't affect the existing array.
Example
# Python program explaining
# numpy.ndarray.copy() function
import numpy as geek
x = geek.array([[0, 1, 2, 3], [4, 5, 6, 7]],
order ='F')
print("x is: \n", x)
# copying x to y
y = x.copy()
print("y is :\n", y)
print("\nx is copied to y")
14
1
# Python program explaining
2
# numpy.ndarray.copy() function
3
4
import numpy as geek
5
6
7
x = geek.array([[0, 1, 2, 3], [4, 5, 6, 7]],
8
order ='F')
9
print("x is: \n", x)
10
11
# copying x to y
12
y = x.copy()
13
print("y is :\n", y)
14
print("\nx is copied to y")
Output
x is:
[[0 1 2 3]
[4 5 6 7]]
y is :
[[0 1 2 3]
[4 5 6 7]]
x is copied to y
Syntax
Syntax: numpy.ndarray.copy(order='C')
Parameters:
- Order : Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if a is Fortran contiguous, 'C' otherwise'K' means match the layout of a as closely as possible
Returns: Copy of an Array
How to make a copy of a NumPy array
To make a copy of a NumPy array in Python, we use ndarray.copy method of the NumPy library
Let us understand it better with an example:
Example: Make a Copy of ndarray
import numpy as geek
x = geek.array([[0, 1, ], [2, 3]])
print("x is:\n", x)
# copying x to y
y = x.copy()
# filling x with 1's
x.fill(1)
print("\n Now x is : \n", x)
print("\n y is: \n", y)
12
1
import numpy as geek
2
x = geek.array([[0, 1, ], [2, 3]])
3
print("x is:\n", x)
4
5
# copying x to y
6
y = x.copy()
7
8
# filling x with 1's
9
x.fill(1)
10
print("\n Now x is : \n", x)
11
12
print("\n y is: \n", y)
Output
x is: [[0 1] [2 3]] Now x is : [[1 1] [1 1]] y is: [[0 1] [2 3]]