NumPy: numpy.copy() function
The numpy.copy() function is used to get an array copy of an given object.
The copy() function can be useful when you want to make changes to an array without modifying the original array. For example, if you want to perform a series of operations on an array and keep the original array intact, you can create a copy of the original array using the copy() function and perform the operations on the copy. This can also be useful when you want to pass a copy of an array to a function without modifying the original array.
|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. (Note that this function and ndarray.copy are very similar, but have different default values for their order= arguments.)||optional|
arr : ndarray
Array interpretation of a.
Example: Shallow and Deep Copy in NumPy
>>> import numpy as np >>> a = np.array ( [2, 3, 4]) >>> b = a >>> c = np.copy(a) >>> a = 15 >>> b == b True
The above code demonstrates shallow and deep copy in NumPy. NumPy arrays support both shallow and deep copying.
Initially, an array 'a' is created with values [2, 3, 4]. Then, a reference to 'a' is assigned to 'b', and a copy of 'a' is created using np.copy() and assigned to 'c'.
When we change the value of the first element of 'a' to 15, it reflects in 'b' as well because 'b' is just a reference to the same memory location as 'a'. So, 'b' also contains [15, 3, 4].
However, the copy 'c' is unaffected by the change in 'a' because it is a deep copy and has its own separate memory location. So, 'c' contains the original values [2, 3, 4].
The expression 'b == b' evaluates to True because the value at index 0 in 'b' is still 15 (same as itself).
Note that, when we modify a, b changes, but not c:
>>> import numpy as np >>> a == c False >>>
Python - NumPy Code Editor:
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join